什么是泛型
泛型就是一种不确定的数据类型。
泛型的优点
- 避免拆箱装箱,提升性能
- 可以避免运行时转换类型出现的错误
泛型方法、泛型约束
Program.cs类:
class Program
{
static void Main(string[] args)
{
int iValue = 123;
string sValue = "456";
DateTime dtValue = DateTime.Now;
object oValue = "789";
//泛型方法
CommonMethod.Show<int>(iValue);
CommonMethod.Show<string>(sValue);
CommonMethod.Show<DateTime>(dtValue);
CommonMethod.Show<object>(oValue);
Chinese chinese = new Chinese()
{
Id = 001,
Name = "赵日天",
Country = "中国",
};
Japanese japanese = new Japanese()
{
Id = 002,
Name = "山本",
Country = "日本",
};
CommonMethod.Introduce<People>(chinese);
CommonMethod.Introduce<People>(japanese);
}
}
CommonMethod.cs类:
public class CommonMethod
{
public static void Show<T>(T tParameter)
{
Console.WriteLine("类型是:{0},值是:{1}",tParameter.GetType().Name, tParameter);
}
public static void Introduce<T>(T tParameter) where T : People
{
Console.WriteLine("我是:"+tParameter.Country+"人");
Console.WriteLine("姓名:" + tParameter.Name);
}
}
Chinese.cs、Japanese.cs和People.cs
public class Chinese : People
{
}
public class Japanese : People
{
}
public class People
{
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
运行结果:
泛型类
GenericClass.cs
class GenericClass<T>
{
private T a;
private T b;
public GenericClass(T a,T b) {
this.a = a;
this.b = b;
}
public T Add() {
dynamic v1 = a;
dynamic v2 = b;
return v1 + v2;
}
}
Program.cs
static void Main(string[] args)
{
//泛型类
GenericClass<int> gcA = new GenericClass<int>(1,2);
int sumA = gcA.Add();
Console.WriteLine("int类型值:"+sumA);
GenericClass<string> gcB = new GenericClass<string>("字符", "串");
string sumB = gcB.Add();
Console.WriteLine("string类型值:" + sumB);
}
运行结果
协变、逆变
协变的作用:解决用泛型包装之后父子关系失效
现有两个类People、Japanese,并且People和Japanese是父子关系
People people = new Japanese(); //语法正确
List<People> peoples = new List<People>();//语法正确
List<People> peoples1 = new List<Japanese>();//语法错误
一个日本人是人,按理说一群日本人属于一群人,那为什么一群日本人就不是一群人了呢?因为在语义上是正确的的,但在语法上是错误的,List<People>是一个类,List<Japanese>也是一个类,它们两个没有父子关系。
可以通过下面代码解决:
List<People> peoples2 = new List<Japanese>().Select(s=>(People)s).ToList();
也可以通过协变来解决
IEnumerable<People> birdList1 = new List<People>();
IEnumerable<People> birdList2 = new List<Japanese>();
逆变的作用:可以在右边用上父类
List<Japanese> japaneses = new List<Japanese>();//语法正确
List<Japanese> japaneses1 = new List<People>();//语法错误
可以通过逆变来解决右边无法使用父类的问题:
Action<Japanese> act = new Action<People>((People i) => { });
泛型接口、泛型委托和泛型方法、泛型类几乎都差不多,在这就不多写了
demo地址:https://github.com/wangongshen/Generic.git