预览加载中,请您耐心等待几秒...
1/10
2/10
3/10
4/10
5/10
6/10
7/10
8/10
9/10
10/10

在线预览结束,喜欢就下载吧,查找使用更方便

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

HYPERLINK"http://www.cnblogs.com/kid-li/archive/2006/11/29/577045.html"C#泛型编程 泛型:通过参数化类型来实现在同一份代码上操作多种数据类型。利用“参数化类型”将类型抽象化,从而实现灵活的复用。 例子代码: classProgram { staticvoidMain(string[]args) { intobj=2; Test<int>test=newTest<int>(obj); Console.WriteLine("int:"+test.obj); stringobj2="helloworld"; Test<string>test1=newTest<string>(obj2); Console.WriteLine("String:"+test1.obj); Console.Read(); } } classTest<T> { publicTobj; publicTest(Tobj) { this.obj=obj; } } 输出结果是: int:2 String:helloworld 程序分析: 1、Test是一个泛型类。T是要实例化的范型类型。如果T被实例化为int型,那么成员变量obj就是int型的,如果T被实例化为string型,那么obj就是string类型的。 2、根据不同的类型,上面的程序显示出不同的值。 C#泛型机制: C#泛型能力有CLR在运行时支持:C#泛型代码在编译为IL代码和元数据时,采用特殊的占位符来表示范型类型,并用专有的IL指令支持泛型操作。而真正的泛型实例化工作以“on-demand”的方式,发生在JIT编译时。 看看刚才的代码中Main函数的元数据 .methodprivatehidebysigstaticvoidMain(string[]args)cilmanaged { .entrypoint //Codesize79(0x4f) .maxstack2 .localsinit([0]int32obj, [1]classCSharpStudy1.Test`1<int32>test, [2]stringobj2, [3]classCSharpStudy1.Test`1<string>test1) IL_0000:nop IL_0001:ldc.i4.2 IL_0002:stloc.0 IL_0003:ldloc.0 IL_0004:newobjinstancevoidclassCSharpStudy1.Test`1<int32>::.ctor(!0) IL_0009:stloc.1 IL_000a:ldstr"int:" IL_000f:ldloc.1 IL_0010:ldfld!0classCSharpStudy1.Test`1<int32>::obj IL_0015:box[mscorlib]System.Int32 IL_001a:callstring[mscorlib]System.String::Concat(object, object) IL_001f:callvoid[mscorlib]System.Console::WriteLine(string) IL_0024:nop IL_0025:ldstr"helloworld" IL_002a:stloc.2 IL_002b:ldloc.2 IL_002c:newobjinstancevoidclassCSharpStudy1.Test`1<string>::.ctor(!0) IL_0031:stloc.3 IL_0032:ldstr"String:" IL_0037:ldloc.3 IL_0038:ldfld!0classCSharpStudy1.Test`1<string>::obj IL_003d:callstring[mscorlib]System.String::Concat(string, string) IL_0042:callvoid[mscorlib]System.Console::WriteLine(string) IL_0047:nop IL_0048:callint32[mscorlib]System.Console::Read() IL_004d:pop IL_004e:ret }//endofmethodProgram::Main 再来看看Test类中构造函数的元数据 .methodpublichidebysigspecialnamertspecialname instancevoid.ctor(!Tobj)cilmanaged { //Codesize17(0x11) .maxstack8 IL_0000:ld