泛型的作用:
泛型方法解决用一个方法,满足不同参数类型做相同的事儿。
没有写死参数类型,调用的时候才指定的类型。
延迟声明:把参数类型的声明推迟到调用。推迟一切可以推迟的~~ 延迟思想
语法及调用:
1、泛型方法
class Program
{
static void Main(string[] args)
{
try
{
People generic = new People();
//generic.Show<int>(12);//调用时可省略<int>
generic.Show<int>(12);
Console.ReadKey();
}
catch (Exception er)
{
throw;
}
}
}
public class People
{
public void Show<T>(T t1)
{
Console.WriteLine($"T的类型是:{typeof(T)}");
Console.WriteLine($"参数类型是:{t1.GetType().Name}");
Console.WriteLine($"参数是:{t1.ToString()}");
}
}
输出结果:
2、泛型类
class Program
{
static void Main(string[] args)
{
try
{
People<int> generic = new People<int>();
generic.Show(12);
Console.ReadKey();
}
catch (Exception er)
{
throw;
}
}
}
public class People<T>
{
public void Show(T t1)
{
Console.WriteLine($"T的类型是:{typeof(T)}");
Console.WriteLine($"参数类型是:{t1.GetType().Name}");
Console.WriteLine($"参数是:{t1.ToString()}");
}
}
输出结果:
输出结果与泛型方法相同。泛型类可以定义多个,名字随意起,但不要用关键字 也不要跟别的类型冲突。例如:
public class People<T,S,F>。泛型方法相同。
泛型约束:
不同的参数类型都能进来;任何类型都能过来,你知道我是谁?
没有约束,也就没有自由
泛型约束--基类约束(不能是sealed)
可以使用基类的一切属性方法
强制保证T一定是基类或者基类的子类
语法及调用:
class Program
{
static void Main(string[] args)
{
try
{
HeBei heBei = new HeBei()
{
Name="张三",
Province="中国河北省"
};
HeNan heNan = new HeNan()
{
Name = "李四",
Province = "中国河南省"
};
NewYork newYork = new NewYork()
{
Name = "JK",
Province = "美国纽约"
};
Constraint.Show(heBei);
Constraint.Show(heNan);
//Constraint.Show(newYork);//错误:类型“Bll.People.NewYork”不能用作泛型类型
//或方法“Constraint.Show<T>(T)”中的类型参数“T”。
//没有从“Bll.People.NewYork”到
//“Bll.People.Chinese”的隐式引用转换。
Console.ReadKey();
}
catch (Exception er)
{
throw;
}
}
}
public class Constraint
{
public static void Show<T>(T t) where T: Chinese
{
t.Show();
}
}
public abstract class Chinese
{
public abstract string Name { get; set; }
public abstract string Province { get; set; }
public abstract void Show();
}
public class NewYork
{
public string Name { get; set; }
public string Province { get; set; }
public void Show()
{
Console.WriteLine($"我的名字叫{Name},我是{Province}人。");
}
}
public class HeNan : Chinese
{
public override string Name { get; set; }
public override string Province { get; set; }
public override void Show()
{
Console.WriteLine($"我的名字叫{Name},我是{Province}人。");
}
}
public class HeBei : Chinese
{
public override string Name { get; set; }
public override string Province { get; set; }
public override void Show()
{
Console.WriteLine($"我的名字叫{Name},我是{Province}人。");
}
}
输出结果:
泛型约束可以是基类约束、接口约束、值类型约束(where T : struct)、引用类型约束(where T : class)和无参构造函数约束(where T : new())。也可以多类型约束,例如:where T : Chinese, new()