转泛型

来自:http://www.cnblogs.com/kid-li/archive/2006/11/29/577045.html

泛型:通过参数化类型来实现在同一份代码上操作多种数据类型。利用“参数化类型”将类型抽象化,从而实现灵活的复用。

例子代码:

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继承的公有成员。如下图:

泛型接口:

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

泛型委托:

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

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,如下图:

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

基类约束:

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++模板那样的基于签名的隐式约束。

时间: 2024-07-30 16:31:27

转泛型的相关文章

.NET编程01(泛型)

一:Object 类型:一切类型的父类,通过继承,子类拥有父类一切属性和行为:任何父类出现的地方,都可以用子类来代替: 用一个方法来完成多个方法做的事 /// <summary>    /// 普通方法类    /// </summary>    public class CommonMethod    {        /// <summary>        /// 打印个int值        /// </summary>        /// <

c#系统泛型委托

Action<T> 无返回值的系统泛型委托 namespace ConsoleApp1 { public class UserInfo { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } class Program { private static List<UserInfo> getInit() { return new List<User

泛型2

万用字符(wildcard) 以动物Animal类为例,怎样才能创建出一种ArrayList<?>里面既可以保存ArrayList<Dog>,又可以保存ArrayList<Cat>? public void takeAnimals(ArrayList<? extends Animal> animals){  //泛型中extends同时代表继承和实现. for(Animal a : animals){ a.eat(); } } 我们可以这样调用该函数: Ar

通过反射了解集合泛型的本质

通过反射了解集合泛型的本质 import java.lang.reflect.Method; import java.util.ArrayList; /** * 通过反射了解集合泛型的本质 * @author shm * */ public class MethodDemo02 { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("hello"); list.add(

构造方法中使用泛型

------------siwuxie095 构造方法中使用泛型: 构造方法可以为类中的属性初始化,如果类中的属性通过泛型指定,而又需要 通过构造方法设置属性内容的时候,构造方法的定义与之前并无不同,不需要 像声明类那样指定泛型 package com.siwuxie095.generic; class Context<T>{ private T value; public Context(T value) { this.value=value; } public T getValue() {

泛型委托当参数传递

假如有一个Person类: public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Title { get; set; } } 执行一个方法: /// <summary> /// 传递一个泛型委托方法 /// </summary> /// <param name="acti

类库,委托,is和as运算符,泛型集合

类库:其实就是一堆类文件,只不过用户看不到这些类的源代码,保密性好. 优点:保密性好缺点:如果这个方法不好用,使用者无法自己去更改它. 类文件是.cs    类库是.dll 新建项目为类库,在debug文件夹下找到dll文件 委托:委托可以理解为:函数的指针 关键词:delegate 声明委托类型:public delegate int FirstDel(int a, int b); FirstDel不是类,是委托变量,不能实例化(不能new), 创建委托变量:FirstDel 名字 = 与这个

泛型委托

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 泛型委托 { public delegate int DelCompare<T>(T t1, T t2); // public delegate int DelCompare(object o1, object o2); class Progra

java 16-8 泛型高级之通配符

泛型高级(通配符) ?:任意类型,如果没有明确,那么就是Object以及任意的Java类了 ? extends E:向下限定,E及其子类 ? super E:向上限定,E极其父类 1 import java.util.ArrayList; 2 import java.util.Collection; 3 public class GenericDemo { 4 public static void main(String[] args) { 5 // 泛型如果明确的写的时候,前后必须一致 6 C

蓝鸥Unity开发基础二——课时21 泛型

本节课我们来学习C#中的泛型,泛型是一个特殊的类型,它可以最大限度的重用我们的代码! 推荐视频讲师博客:http://11165165.blog.51cto.com/ 使用泛型能够最大限度的重用代码,保护类型安全,提高性能 泛型成员因为类型的不确定性,不能使用算术运算符,比较运算符 类型参数可以有多个,可以是编译器能够识别的任何类型 类型参数的名字不能够随便起,不能重名 一.数组类Array using System; namespace Lesson_21{    //数组类Array