欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#泛型编程介绍

程序员文章站 2024-02-18 15:32:58
例子代码: 复制代码 代码如下:class program    {      ...

例子代码:

复制代码 代码如下:

class program
    {
        static void main(string[] args)
        {
            int obj = 2;
            test<int> test = new test<int>(obj);
            console.writeline("int:" + test.obj);
            string obj2 = "hello world";
            test<string> test1 = new test<string>(obj2);
            console.writeline("string:" + test1.obj);
            console.read();
        }
    }
    class test<t>
    {
        public t obj;
        public test(t obj)
        {
            this.obj = obj;
        }
}

输出结果是:

int:2
string:hello world

程序分析:

1、  test是一个泛型类。t是要实例化的范型类型。如果t被实例化为int型,那么成员变量obj就是int型的,如果t被实例化为string型,那么obj就是string类型的。

2、  根据不同的类型,上面的程序显示出不同的值。

c#泛型机制:

c#泛型能力有clr在运行时支持:c#泛型代码在编译为il代码和元数据时,采用特殊的占位符来表示范型类型,并用专有的il指令支持泛型操作。而真正的泛型实例化工作以“on-demand”的方式,发生在jit编译时。

看看刚才的代码中main函数的元数据

复制代码 代码如下:

.method private hidebysig static void  main(string[] args) cil managed
{
  .entrypoint
  // code size       79 (0x4f)
  .maxstack  2
  .locals init ([0] int32 obj,
           [1] class csharpstudy1.test`1<int32> test,
           [2] string obj2,
           [3] class csharpstudy1.test`1<string> test1)
  il_0000:  nop
  il_0001:  ldc.i4.2
  il_0002:  stloc.0
  il_0003:  ldloc.0
  il_0004:  newobj     instance void class csharpstudy1.test`1<int32>::.ctor(!0)
  il_0009:  stloc.1
  il_000a:  ldstr      "int:"
  il_ 000f:  ldloc.1
  il_0010:  ldfld      !0 class csharpstudy1.test`1<int32>::obj
  il_0015:  box        [mscorlib]system.int32
  il_ 001a:  call       string [mscorlib]system.string::concat(object,
                                                              object)
  il_ 001f:  call       void [mscorlib]system.console::writeline(string)
  il_0024:  nop
  il_0025:  ldstr      "hello world"
  il_ 002a:  stloc.2
  il_002b:  ldloc.2
  il_ 002c:  newobj     instance void class csharpstudy1.test`1<string>::.ctor(!0)
  il_0031:  stloc.3
  il_0032:  ldstr      "string:"
  il_0037:  ldloc.3
  il_0038:  ldfld      !0 class csharpstudy1.test`1<string>::obj
  il_003d:  call       string [mscorlib]system.string::concat(string,
                                                              string)
  il_0042:  call       void [mscorlib]system.console::writeline(string)
  il_0047:  nop
  il_0048:  call       int32 [mscorlib]system.console::read()
  il_004d:  pop
  il_004e:  ret
} // end of method program::main

    再来看看test类中构造函数的元数据

复制代码 代码如下:

.method public hidebysig specialname rtspecialname
        instance void  .ctor(!t obj) cil managed
{
  // code size       17 (0x11)
  .maxstack  8
  il_0000:  ldarg.0
  il_0001:  call       instance void [mscorlib]system.object::.ctor()
  il_0006:  nop
  il_0007:  nop
  il_0008:  ldarg.0
  il_0009:  ldarg.1
  il_ 000a:  stfld      !0 class consolecsharptest1.test`1<!t>::obj
  il_ 000f:  nop
  il_0010:  ret
} // end of method test`1::.ctor

1、第一轮编译时,编译器只为test<t>类型产生“泛型版”的il代码与元数据——并不进行泛型的实例化,t在中间只充当占位符。例如:test类型元数据中显示的<!t>
2、jit编译时,当jit编译器第一次遇到test<int>时,将用int替换“范型版”il代码与元数据中的t——进行泛型类型的实例化。例如:main函数中显示的<int>
3、clr为所有类型参数为“引用类型”的泛型类型产生同一份代码;但是如果类型参数为“值类型”,对每一个不同的“值类型”,clr将为其产生一份独立的代码。因为实例化一个引用类型的泛型,它在内存中分配的大小是一样的,但是当实例化一个值类型的时候,在内存中分配的大小是不一样的。

c#泛型特点:

1、如果实例化泛型类型的参数相同,那么jit编辑器会重复使用该类型,因此c#的动态泛型能力避免了c++静态模板可能导致的代码膨胀的问题。
2、c#泛型类型携带有丰富的元数据,因此c#的泛型类型可以应用于强大的反射技术。
3、c#的泛型采用“基类、接口、构造器,值类型/引用类型”的约束方式来实现对类型参数的“显示约束”,提高了类型安全的同时,也丧失了c++模板基于“签名”的隐式约束所具有的高灵活性

c#泛型继承:

c#除了可以单独声明泛型类型(包括类与结构)外,也可以在基类中包含泛型类型的声明。但基类如果是泛型类,它的类型要么以实例化,要么来源于子类(同样是泛型类型)声明的类型参数,看如下类型

class c<u,v>
class d:c<string,int>
class e<u,v>:c<u,v>
class f<u,v>:c<string,int>
class g:c<u,v> //非法

e类型为c类型提供了u、v,也就是上面说的来源于子类

f类型继承于c<string,int>,个人认为可以看成f继承一个非泛型的类

g类型为非法的,因为g类型不是泛型,c是泛型,g无法给c提供泛型的实例化

泛型类型的成员:

泛型类型的成员可以使用泛型类型声明中的类型参数。但类型参数如果没有任何约束,则只能在该类型上使用从system.object继承的公有成员。如下图:

C#泛型编程介绍

泛型接口:

泛型接口的类型参数要么已实例化,要么来源于实现类声明的类型参数

泛型委托:

泛型委托支持在委托返回值和参数上应用参数类型,这些参数类型同样可以附带合法的约束

复制代码 代码如下:

delegate bool mydelegate<t>(t value);
class myclass
{
    static bool f(int i){...}
    static bool g(string s){...}
    static void main()
    {
        mydelegate<string> p2 = g;
        mydelegate<int> p1 = new mydelegate<int>(f);
    }
}

泛型方法:

1、c#泛型机制只支持“在方法声明上包含类型参数”——即泛型方法。
2、c#泛型机制不支持在除方法外的其他成员(包括属性、事件、索引器、构造器、析构器)的声明上包含类型参数,但这些成员本身可以包含在泛型类型中,并使用泛型类型的类型参数。
3、泛型方法既可以包含在泛型类型中,也可以包含在非泛型类型中。

泛型方法声明:如下

public static int functionname<t>(t value){...}

泛型方法的重载:

public void function1<t>(t a);
public void function1<u>(u a);

这样是不能构成泛型方法的重载。因为编译器无法确定泛型类型t和u是否不同,也就无法确定这两个方法是否不同

public void function1<t>(int x);
public void function1(int x);

这样可以构成重载

public void function1<t>(t t) where t:a;
public void function1<t>(t t) where t:b;

这样不能构成泛型方法的重载。因为编译器无法确定约束条件中的a和b是否不同,也就无法确定这两个方法是否不同

泛型方法重写:

在重写的过程中,抽象类中的抽象方法的约束是被默认继承的。如下:

复制代码 代码如下:

abstract class base
{
    public abstract t f<t,u>(t t,u u) where u:t;
    public abstract t g<t>(t t) where t:icomparable;
}
class myclass:base
{
    public override x f<x,y>(x x,y y){...}
    public override t g<t>(t t) where t:icomparable{}
}

对于myclass中两个重写的方法来说
f方法是合法的,约束被默认继承
g方法是非法的,指定任何约束都是多余的

泛型约束:

1、c#泛型要求对“所有泛型类型或泛型方法的类型参数”的任何假定,都要基于“显式的约束”,以维护c#所要求的类型安全。
2、“显式约束”由where子句表达,可以指定“基类约束”,“接口约束”,“构造器约束”,“值类型/引用类型约束”共四种约束。
3、“显式约束”并非必须,如果没有指定“显式约束”,范型类型参数将只能访问system.object类型中的公有方法。例如:在开始的例子中,定义的那个obj成员变量。比如我们在开始的那个例子中加入一个test1类,在它当中定义两个公共方法func1、func2,如下图:

C#泛型编程介绍

下面就开始分析这些约束:

基类约束:

复制代码 代码如下:

class a
    {
        public void func1()
        { }
    }
    class b
    {
        public void func2()
        { }
    }
    class c<s, t>
        where s : a
        where t : b
    {
        public c(s s,t t)
        {
            //s的变量可以调用func1方法
            s.func1();
            //t的变量可以调用func2方法
            t.func2();
        }
    }


接口约束:

复制代码 代码如下:

interface ia<t>
    {
        t func1();
    }
    interface ib
    {
        void func2();
    }
    interface ic<t>
    {
        t func3();
    }
    class myclass<t, v>
        where t : ia<t>
        where v : ib, ic<v>
    {
        public myclass(t t,v v)
        {
            //t的对象可以调用func1
            t.func1();
            //v的对象可以调用func2和func3
            v.func2();
            v.func3();
        }
    }


构造器约束:

复制代码 代码如下:

class a
        {
            public a()
            { }
        }
        class b
        {
            public b(int i)
            { }
        }
        class c<t> where t : new()
        {
            t t;
            public c()
            {
                t = new t();
            }
        }
        class d
        {
            public void func()
            {
                c<a> c = new c<a>();
                c<b> d = new c<b>();
            }
        }


    d对象在编译时报错:the type b must have a public parameterless constructor in order to use it as parameter 't' in the generic type or method c<t>

注意:c#现在只支持无参的构造器约束

    此时由于我们为b类型写入了一个有参构造器,使得系统不会再为b自动创建一个无参的构造器,但是如果我们将b类型中加一个无参构造器,那么对象d的实例化就不会报错了。b类型定义如下:

   

复制代码 代码如下:

        class b
        {
            public b()
            { }
            public b(int i)
            { }
        }

值类型/引用类型:

复制代码 代码如下:

public struct a { }
        public class b { }
        public class c<t> where t : struct
        {
        }
        c<a> c1 = new c<a>();
        c<b> c2 = new c<b>();

    c2对象在编译时报错:the type 'b' must be a non-nullable value type in order to use it as parameter 't' in the generic type or methor 'c<t>'

总结:

1、c#的泛型能力由clr在运行时支持,它既不同于c++在编译时所支持的静态模板,也不同于java在编译器层面使用“擦拭法”支持的简单的泛型。
2、c#的泛型支持包括类、结构、接口、委托四种泛型类型,以及方法成员。
3、c#的泛型采用“基类,接口,构造器,值类型/引用类型”的约束方式来实现对类型参数的“显式约束”,它不支持c++模板那样的基于签名的隐式约束。