C# 泛型方法
static void Main(string[] args)
{
TestClass cls = new TestClass();
cls.GetType("123");
Student stu = new 泛型方法.Student();
stu.Name = "王五";
stu.Age = 23;
//只有在使用才能确定类型
cls.GetParam<Student>(stu);
Console.ReadKey();
}
public class TestClass
{
/// <summary> /// object是任何类型的父类,都可以用子类的元素代替,实质进行类型的转换消耗了性能 /// </summary> /// <param name="tParam"></param> public void GetType(object tParam) {
// tParam参数只有四个方法调用, Console.WriteLine("类型为:"+tParam.GetType()); } /// <summary> /// 泛型方法,T参数类型只有在使用时候才能确定类型,泛型方法进行约束,则T类型必须是People或其子类,否则程序会报错 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tParam"></param> public void ShowGeneric<T>(T tParam) where T :People { Console.WriteLine("类型为:" + tParam.GetType() + " ,姓名为:" + tParam.Name);
//SayHi()是People父类的方法 tParam.SayHi(); } /// <summary> /// 泛型方法没有约束的 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tParam"></param> public void GetParam<T>(T tParam) {
// is 用于判断类型 if (tParam is Student) { Student stu = tParam as Student; Console.WriteLine("类型为:" + tParam.GetType() + "其他的" + stu.Name); } else Console.WriteLine("类型为:" + tParam.GetType()); }
}