1.以下代码中的show方法,object 和泛型的输出结果完全相同,但是我们尽量要用泛型,
因为object 参数在进行传入的时候,会进行装箱和拆箱,这样效率会变慢,而泛型实质是语法糖。它是编译器提供的功能,
在调用的生成对应的副本,例如:泛型传入的类型是int它会生成对应的 public void Show(int t){}方法,
泛型编译后是 Show~1();
public class People
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public void Show(int t)
{
Console.WriteLine(t.GetType());
}
public void Show(string t)
{
Console.WriteLine(t.GetType());
}
public void Show(object t)
{
Console.WriteLine(t.GetType());
}
public void Show<T>(T t)
{
Console.WriteLine(t.GetType());
}
}
2.泛型的约束
2.1泛型方法约束
public void MyFunction<T>(T t) where T : class, new()//T引用类型 默认值是null ,并且可以new 一个该类型的对象
{
T t1 = new T();
}
public void MyFunction1<T>(T t) where T : struct // 值类型,一般数值默认值是0,但是DateTime 默认值不是0
{
}
2.2泛型类
public class People<T, W, S>
{
public T Id { get; set; }
public W Name { get; set; }
public S Age { get; set; }
}
2.3泛型接口
public interface People<T, W, S>
{
T getStudent();
T getStudentById(W w);
}