IComparable<>,IFormattable,IEnumerable<>接口使用

来源:互联网 发布:淘宝评分影响 编辑:程序博客网 时间:2024/04/29 16:01

1 Racer类

    [Serializable]    public class Racer : IComparable<Racer>, IFormattable    {                           public Racer(string firstName = null, string lastName = null, string country = null,            int starts = 0, int wins = 0, IEnumerable<int> years = null, IEnumerable<string> cars = null)        {            this.FirstName = firstName;            this.LastName = lastName;            this.Country = country;            this.Starts = starts;            this.Wins = wins;            var yearList = new List<int>();            foreach (int year in years)            {                yearList.Add(year);            }            this.Years = yearList.ToArray();            var carList = new List<string>();            foreach (string car in cars)            {                carList.Add(car);            }            this.Cars = carList.ToArray();        }        public string FirstName { get; set; }        public string LastName { get; set; }        public string Country { get; set; }        public int Starts { get; set; }        public int Wins { get; set; }        public int[] Years { get; private set; }        public string[] Cars { get; private set; }        public int CompareTo(Racer r)        {            if (r == null) throw new ArgumentNullException("r");            return this.LastName.CompareTo(r.LastName);        }        public override string ToString()        {            return string.Format("{0} {1}", FirstName, LastName);        }        public string ToString(string format)        {            return ToString(format, null);        }        public string ToString(string format, IFormatProvider formatProvider)        {            switch (format)            {                case "L":                    return LastName;                case "F":                    return FirstName;                case "C":                    return Country;                case "W":                    return Wins.ToString();                case "S":                    return Starts.ToString();                default:                    throw new FormatException(string.Format("format:{0} not supported!", format));            }        }    }


2 Team类

    public class Team    {        public Team(string name, params int[] years)        {            this.Name = name;            this.Years = years;        }        private string Name { get; set; }        private int[] Years { get; set; }    }

3 初始化

            Racer racer = new Racer("Nino", "Farina", "Italy", 33, 5,                new int[] { 1950 }, new string[] { "Alfa Romeo", "Maserati" });            Team team1 = new Team("Vanwall", 1955);            Team team2 = new Team("Cooper", 1959, 1960);

0 0