C# 泛型编程之泛型类、泛型方法、泛型约束

泛型方法html

    在C#2.0中,方法能够定义特定于其执行范围的泛型参数,以下所示:编程

复制代码
    public class MyClass<T>
    {
        //指定MyMethod方法用以执行类型为X的参数
        public void MyMethod<X>(X x) 
        {
            //
        }

        //此方法也可不指定方法参数
        public void MyMethod<X>() 
        {
            //
        }
    }   
复制代码

    即便包含类不适用泛型参数,你也能够定义方法特定的泛型参数,以下所示:数组

复制代码
    public class MyClass
    {
        //指定MyMethod方法用以执行类型为X的参数
        public void MyMethod<X>(X x) 
        {
            //
        }

        //此方法也可不指定方法参数
        public void MyMethod<X>() 
        {
            //
        }
    }
复制代码
    注意:属性和索引器不能指定本身的泛型参数,它们只能使用所属类中定义的泛型参数进行操做。
    在调用泛型方法的时候,你能够提供要在调用场所使用的类型,以下所示:
//调用泛型方法
MyClass myClass = new MyClass();
myClass.MyMethod<int>(3);
    泛型推理:在调用泛型方法时,C#编译器足够聪明,基于传入的参数类型来推断出正确的类型,而且它容许彻底省略类型规范,以下所示:
//泛型推理机制调用泛型方法
MyClass myClass = new MyClass();
myClass.MyMethod(3);
    注意:泛型方法没法只根据返回值的类型推断出类型,代码以下:
复制代码
     public GenericMethodDemo()
     {        
        MyClass myClass = new MyClass();
        /****************************************************
        没法从用法中推理出方法“GenericMethodDemo.MyClass.MyMethod<T>()”的类型参数。
        请尝试显式指定类型参数。
        ***************************************************/
        int number = myClass.MyMethod();
     }

    public class MyClass
    {
        public T MyMethod<T>() 
        {
            //
        }
    }
复制代码
    泛型方法中泛型参数的约束,以下:
复制代码
    public class MyClass
    {
        
        public void MyMethod<X>(X x) where X:IComparable<X>
        {
            //
        }
    }
复制代码
    您没法为类级别的泛型参数提供方法级别的约束。类级别泛型参数的全部约束都必须在类做用范围中定义,代码以下所示
复制代码
    public class MyClass<T>
    {
        
        public void MyMethod<X>(X x,T t) where X:IComparable<X> where T:IComparer<T>
        {
            //
        }
    }
复制代码
 
而下面的代码是正确的
复制代码
    public class MyClass<T> where T:IComparable<T>
    {
        
        public void MyMethod<X>(X x,T t) where X:IComparable<X> 
        {
            //
        }
    }
复制代码
    泛型参数虚方法的重写:子类方法必须从新定义该方法特定的泛型参数,代码以下
复制代码
    public class MyBaseClass
    {
        public virtual void SomeMethod<T>(T t)
        {
            //
        }
    }
    public class MyClass :MyBaseClass
    {
        public override void SomeMethod<X>(X x)
        {
            
        }
    }
复制代码
 
同时子类中的泛型方法不能重复基类泛型方法的约束,这一点和泛型类中的虚方法重写是有区别的,代码以下
复制代码
    public class MyBaseClass
    {
        public virtual void SomeMethod<T>(T t) where T:new()
        {
            //
        }
    }
    public class MyClass :MyBaseClass
    {
        //正确写法
        public override void SomeMethod<X>(X x)
        {
            
        }

        ////错误 重写和显式接口实现方法的约束是从基方法继承的,所以不能直接指定这些约束
        //public override void SomeMethod<X>(X x) where X:new()
        //{

        //}
    }
复制代码
    子类方法调用虚拟方法的基类实现:它必须指定要代替泛型基础方法类型所使用的类型实参。你能够本身显式的指定它,也能够依靠类型推理(若是可能的话)代码以下:
复制代码
    public class MyBaseClass
    {
        public virtual void SomeMethod<T>(T t) where T:new()
        {
            //
        }
    }
    public class MyClass :MyBaseClass
    {
        //正确写法
        public override void SomeMethod<X>(X x)
        {
            base.SomeMethod<X>(x);
            base.SomeMethod(x);
        }
    }
复制代码
泛型委托
    在某个类中定义的委托能够使用该类的泛型参数,代码以下
复制代码
    public class MyClass<T>
    {
        public delegate void GenericDelegate(T t);
        public void SomeMethod(T t)
        {
 
        }
    }
    public GenericMethodDemo()
    {
        MyClass<int> obj = new MyClass<int>();
        MyClass<int>.GenericDelegate del;
        del = new MyClass<int>.GenericDelegate(obj.SomeMethod);
        del(3);
    }
复制代码
    委托推理:C#2.0使你能够将方法引用的直接分配转变为委托变量。将上面的代码改造以下
复制代码
public class MyClass<T>
    {
        public delegate void GenericDelegate(T t);
        public void SomeMethod(T t)
        {
 
        }
    }
    public GenericMethodDemo()
    {
        MyClass<int> obj = new MyClass<int>();
        MyClass<int>.GenericDelegate del;

        //委托推理
      del = obj.SomeMethod;
        del(3);
     }    
复制代码
    泛型委托的约束:委托级别的约束只在声明委托变量和实例化委托时使用,相似于在类型和方法的做用范围中实施的其余任何约束。
泛型和反射
    在Net2.0当中,扩展了反射以支持泛型参数。类型Type如今能够表示带有特定类型的实参(或绑定类型)或未指定类型的泛型(或称未绑定类型)。像C#1.1中那样,您能够经过使用typeof运算符或经过调用每一个类型支持的GetType()来得到任何类型的Type。代码以下:
 LinkedList<int> list = new LinkedList<int>();
 Type type1 = typeof(LinkedList<int>);
 Type type2 = list.GetType();
 Response.Write(type1 == type2);
 
     typeof和GetType()也能够对泛型参数进行操做,以下
复制代码
public class MyClass<T>
{
    public void SomeMethod(T t)
    {
        Type type = typeof(T);
        HttpContext.Current.Response.Write(type==t.GetType());
    }
}
复制代码
    typeof还能够对未绑定的泛型进行操做,代码以下
复制代码
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Type unboundType = typeof(MyClass<>);
            Response.Write(unboundType.ToString());
        }
    }

    public class MyClass<T>
    {
        public void SomeMethod(T t)
        {
            Type type = typeof(T);
            HttpContext.Current.Response.Write(type==t.GetType());
        }
    }
复制代码
 
    请注意"<>"的用法。要对带有多个类型参数的未绑定泛型类进行操做,请在"<>"中使用","
    Type类中添加了新的方法和属性,用于提供有关该类型的泛型方面的反射信息,见MSDN。
 
 

.net泛型约束  

 

所谓泛型,即经过参数化类型来实如今同一份代码上操做多种数据类型。泛型编程是一种编程范式,它利用“参数化类型”将类型抽象化,从而实现更为灵活的复用。ide

在定义泛型类时,能够对客户端代码可以在实例化类时用于类型参数的类型种类施加限制。若是客户端代码尝试使用某个约束所不容许的类型来实例化类,则会产生编译时错误。这些限制称为约束。约束是使用 where 上下文关键字指定的。函数

下表列出了五种类型的约束:spa

 

约束 说明

T:struct.net

类型参数必须是值类型。能够指定除 Nullable 之外的任何值类型。code

T:classhtm

类型参数必须是引用类型,包括任何类、接口、委托或数组类型。blog

T:new()

类型参数必须具备无参数的公共构造函数。当与其余约束一块儿使用时,new() 约束必须最后指定。

T:<基类名>

类型参数必须是指定的基类或派生自指定的基类。

T:<接口名称>

类型参数必须是指定的接口或实现指定的接口。能够指定多个接口约束。约束接口也能够是泛型的。

T:U

为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。这称为裸类型约束.

 ---------------------------------------

一.派生约束

1.常见的

public class MyClass5<T> where T :IComparable { }

2.约束放在类的实际派生以后

public class B { }

public class MyClass6<T> : B where T : IComparable { }

3.能够继承一个基类和多个接口,且基类在接口前面

public class B { }

public class MyClass7<T> where T : B, IComparable, ICloneable { }

二.构造函数约束

1.常见的

public class MyClass8<T> where T :  new() { }

2.能够将构造函数约束和派生约束组合起来,前提是构造函数约束出如今约束列表的最后

public class MyClass8<T> where T : IComparable, new() { }

三.值约束

1.常见的

public class MyClass9<T> where T : struct { }

2.与接口约束同时使用,在最前面(不能与基类约束,构造函数约束一块儿使用)

public class MyClass11<T> where T : struct, IComparable { }

四.引用约束

1.常见的

public class MyClass10<T> where T : class { }

五.多个泛型参数

 public class MyClass12<T, U> where T : IComparable  where U : class { }

六.继承和泛型

public class B<T>{ }

1. 在从泛型基类派生时,能够提供类型实参,而不是基类泛型参数

    public class SubClass11 : B<int>
    { }

2.若是子类是泛型,而非具体的类型实参,则能够使用子类泛型参数做为泛型基类的指定类型

    public class SubClass12<R> : B<R>
    { }

3.在子类重复基类的约束(在使用子类泛型参数时,必须在子类级别重复在基类级别规定的任何约束)
    public class B<T> where T : ISomeInterface { }
    public class SubClass2<T> : B<T> where T : ISomeInterface { }

4.构造函数约束
    public class B<T> where T : new()
    {
        public T SomeMethod()
        {
            return new T();
        }
    }
    public class SubClass3<T> : B<T> where T : new(){ }

七.泛型方法(C#2.0泛型机制支持在"方法声名上包含类型参数",这就是泛型方法)

1.泛型方法既能够包含在泛型类型中,又能够包含在非泛型类型中

public class MyClass5
    {

        public void MyMethod<T>(T t){ }
    }

2.泛型方法的声明与调用

public class MyClass5
    {
        public void MyMethod<T>(T t){ }
    }
    public class App5
    {
        public void CallMethod()
        {
            MyClass5 myclass5 = new MyClass5();
            myclass5.MyMethod<int>(3);
        }
    }

3.泛型方法的重载

 //第一组重载
 void MyMethod1<T>(T t, int i){ }

 void MyMethod1<U>(U u, int i){ }

//第二组重载
 void MyMethod2<T>(int i){ }
 void MyMethod2(int i){ }

//第三组重载,假设有两个泛型参数
 void MyMethod3<T>(T t) where T : A { }
void MyMethod3<T>(T t) where T : B { }

//第四组重载

public class MyClass8<T,U>
    {
        public T MyMothed(T a, U b)
        {
            return a;
        }
        public T MyMothed(U a, T b)
        {
            return b;
        }
        public int MyMothed(int a, int b)
        {
            return a + b;
        }
    }

4.泛型方法的覆写

(1)public class MyBaseClass1
    {
        public virtual void MyMothed<T>(T t) where T : new() { }
    }
    public class MySubClass1:MyBaseClass1
    {
        public override void MyMothed<T>(T t) //不能重复任何约束
        { }
    }

(2)public class MyBaseClass2
    {
        public virtual void MyMothed<T>(T t)
        { }
    }
    public class MySubClass2 : MyBaseClass2
    {
        public override void MyMothed<T>(T t) //从新定义泛型参数T
        { }
    }

八.虚拟方法

public class BaseClass4<T>
    {
        public virtual T SomeMethod()
        {
            return default(T);
        }
    }
    public class SubClass4 : BaseClass4<int> //使用实参继承的时候方法要使用实参的类型
    {
        public override int SomeMethod()
        {
            return 0;
        }
    }

    public class SubClass5<T> : BaseClass4<T> //使用泛型继承时,方法也是泛型
    {
        public override T SomeMethod()
        {
            return default(T);
        }
    }

九.编译器只容许将泛型参数隐式强制转换到 Object 或约束指定的类型

class MyClass<T> where T : BaseClass, ISomeInterface
    {
        void SomeMethod(T t)
        {
            ISomeInterface obj1 = t;
            BaseClass obj2 = t;
            object obj3 = t;
        }
    }

变通方法:使用临时的 Object 变量,将泛型参数强制转换到其余任何类型

class MyClass2<T>
    {
        void SomeMethod(T t)
        {
            object temp = t;
            BaseClass obj = (BaseClass)temp;
        }
    }

十.编译器容许您将泛型参数显式强制转换到其余任何接口,但不能将其转换到类

class MyClass1<T>
    {
        void SomeMethod(T t)
        {
            ISomeInterface obj1 = (ISomeInterface)t;  
            //BaseClass obj2 = (BaseClass)t;           //不能经过编译
        }
    }

 

十一.使用临时的 Object 变量,将泛型参数强制转换到其余任何类型

class MyClass2<T>
    {
        void SomeMethod(T t)
        {
            object temp = t;
            BaseClass obj = (BaseClass)temp;
        }
    }

十二.使用is和as运算符

public class MyClass3<T>    {        public void SomeMethod(T t)        {            if (t is int) { }            if (t is LinkedList<int>) { }            string str = t as string;            if (str != null) { }            LinkedList<int> list = t as LinkedList<int>;            if (list != null) { }        }    }

相关文章
相关标签/搜索