C# 泛型

Where T:class 泛型类型约束

对于一个定义泛型类型为参数的函数,如果调用时传入的对象为T对象或者为T的子类,在函数体内部如果需要使用T的属性的方法时,我们可以给这个泛型增加约束;

//父类子类的定义
public class ProductEntryInfo
    {
        [Description("商品编号")]
        public int ProductSysNo { get; set; }  
       //more
    }

    public class ProductEntryInfoEx : ProductEntryInfo
    {
       
        [Description("成份")]
        public string Component { get; set; }  
       //more
    }

//方法:
private static string CreateFile<T>(List<T> list) where T:ProductEntryInfo
 { 
   int productSysNo =list[0].ProductSysNo 
 } 

//调用:
List<ProductEntryInfo> peList = new List<ProductEntryInfo>();
string fileName = CreateFile( peList);

List<ProductEntryInfoEx> checkListAll = new List<ProductEntryInfoEx>();   
string fileNameEx = CreateFile(checkListAll);
View Code

这样就可以实现上边的CreateFile方法了

  这样类型参数约束,.NET支持的类型参数约束有以下五种:

    where T : struct  T必须是一个结构类型
    where T : class   T必须是一个类(class)类型
    where T : new()    T必须要有一个无参构造函数
    where T : NameOfBaseClass | T必须继承名为NameOfBaseClass的类
    where T : NameOfInterface | T必须实现名为NameOfInterface的接口

分别提供不同类型的泛型约束。

可以提供类似以下约束

class MyClass<T, U>

    where T : class

    where U : struct

{ }

 

泛型初始化

default(T)

default(T)可以得到该类型的默认值。

C#在类初始化时,会给未显示赋值的字段、属性赋上默认值,但是值变量却不会。值变量可以使用默认构造函数赋值,或者使用default(T)赋值。

默认构造函数是通过 new 运算符来调用的,如下所示:

  1. int myInt = new int();

default(T)如下所示:

  1. int myInt = default(int);

以上语句同下列语句效果相同:

  1. int myInt = 0;

请记住:在 C# 中不允许使用未初始化的变量

之所以会用到default关键字,是因为需要在不知道类型参数为值类型还是引用类型的情况下,为对象实例赋初值。考虑以下代码:

class TestDefault<T>
    {
        public T foo()
        {
            T t = null; //???
            return t;
        }
    }

如果我们用int型来绑定泛型参数,那么T就是int型,那么注释的那一行就变成了 int t = null;显然这是无意义的。为了解决这一问题,引入了default关键字:

class TestDefault<T>
    {
        public T foo()
        {
                return default(T);
        }
    }

 

 

 

 

posted @ 2019-06-15 12:53  peterYong  阅读(1902)  评论(0编辑  收藏  举报