1.泛型约束
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public char Sex { get; set; }
}
public class MyList<T> where T : new()
{
public List<T> list = new List<T>();
public void Add(T item)
{
list.Add(item);
}
}
class Program
{
static void Main(string[] args)
{
MyList<User> myList = new MyList<User>();
myList.Add(new User() { Name = "张三", Age = 10, Sex = ‘女‘ });
myList.Add(new User() { Name = "李四", Age = 15, Sex = ‘男‘ });
foreach (var item in myList.list)
{
Console.WriteLine("姓名:{0}\t年龄:{1}\t性别:{2}",item.Name,item.Age,item.Sex);
}
}
}
原文:https://www.cnblogs.com/-xyk/p/14616953.html