C#自定义泛型集合
1.泛型约束
- where T : struct 限制类型参数T必须是继承自System.Value.Type。
- where T : class 限制类型参数T必须是引用类型。
- where T : new() 限制类型参数T必须有无参的、公共构造函数。
- where T : NameOfClass限制类型参数T必须继承自某个接口或实现某个接口
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);
}
}
}

浙公网安备 33010602011771号