Home  >  Article  >  Backend Development  >  C# Generic Programming

C# Generic Programming

黄舟
黄舟Original
2016-12-21 14:47:35925browse

Generics: Use parameterized types to operate multiple data types on the same code. Use "parameterized types" to abstract types to achieve flexible reuse. ​​​​Test test = new Test(obj);

                                              ‐               ‐                                                          .

     Console.WriteLine(" String: " + test1.obj);

Console.Read(); Public T obj;

Public Test(T obj)

                                                             This.obj =                                                                                                     

Program analysis:

1. Test is a generic class . T is the generic type to be instantiated. If T is instantiated as type int, then the member variable obj is of type int. If T is instantiated as type string, then obj is of type string.

2. Depending on the type, the above program displays different values.



C# generic mechanism:

C# generic capabilities are supported by CLR at runtime: When C# generic code is compiled into IL code and metadata, special placeholders are used to represent generic types, and special Some IL instructions support generic operations. The real generic instantiation work occurs in an "on-demand" manner during JIT compilation.



Look at the metadata of the Main function in the code just now

.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 test,

[2] string obj2,

              [3] class CSharpStudy1.Test` 1 test1)

IL_0000: nop

IL_0001: ldc.i4.2

IL_0002: stloc.0

IL_0003: ldloc.0

IL_00 04: newobj instance void class CSharpStudy1.Test`1 ::.ctor(!0)

IL_0009: stloc.1

IL_000a: ldstr "int:"

IL_000f: ldloc.1

IL_0010: ldfld !0 class CSharpStudy1. Test`1::obj : IL_0015: BOX [mscorlib] System.int32

IL_001a: call String [mSCORLIB] System.String :: Concat (object,

object)

IL_001F: call void [mscorlib] system.con.con sole :: 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::.ctor(!0)

  IL_0031:  stloc.3

  IL_0032:  ldstr      "String:"

  IL_0037:  ldloc.3

  IL_0038:  ldfld      !0 class CSharpStudy1.Test`1::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::obj

  IL_000f:  nop

  IL_0010:  ret

} // end of method Test`1::.ctor



1、第一轮编译时,编译器只为Test类型产生“泛型版”的IL代码与元数据——并不进行泛型的实例化,T在中间只充当占位符。例如:Test类型元数据中显示的

2、JIT编译时,当JIT编译器第一次遇到Test时,将用int替换“范型版”IL代码与元数据中的T——进行泛型类型的实例化。例如:Main函数中显示的

3、CLR为所有类型参数为“引用类型”的泛型类型产生同一份代码;但是如果类型参数为“值类型”,对每一个不同的“值类型”,CLR将为其产生一份独立的代码。因为实例化一个引用类型的泛型,它在内存中分配的大小是一样的,但是当实例化一个值类型的时候,在内存中分配的大小是不一样的。



C#泛型特点:

1、如果实例化泛型类型的参数相同,那么JIT编辑器会重复使用该类型,因此C#的动态泛型能力避免了C++静态模板可能导致的代码膨胀的问题。

2、C#泛型类型携带有丰富的元数据,因此C#的泛型类型可以应用于强大的反射技术。

3、C#的泛型采用“基类、接口、构造器,值类型/引用类型”的约束方式来实现对类型参数的“显示约束”,提高了类型安全的同时,也丧失了C++模板基于“签名”的隐式约束所具有的高灵活性



C#泛型继承:

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

class C

class D:C

class E:C

class F:C

class G:C  //非法

E类型为C类型提供了U、V,也就是上面说的来源于子类

F类型继承于C,个人认为可以看成F继承一个非泛型的类

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



Members of generic types:

Members of generic types can use type parameters in the generic type declaration. But if the type parameter does not have any constraints, you can only use public members inherited from System.Object on the type. As shown below:




Generic interface:

The type parameters of the generic interface are either instantiated or derived from the type parameters declared by the implementation class



Generic delegate:

Generic delegate supports delegation Parameter types are applied to the return value and parameters. These parameter types can also come with legal constraints

delegate bool MyDelegate(T value);

class MyClass

{

  static bool F(int i){.. .}

static bool G(string s){...}

static void Main()

{

MyDelegate p2 = G;

MyDelegate p1 = new My Delegate( F);

}

}



Generic methods:

1. The C# generic mechanism only supports "containing type parameters on the method declaration" - that is, generic methods.

2. The C# generic mechanism does not support the inclusion of type parameters in the declaration of other members (including properties, events, indexers, constructors, destructors) except methods, but these members themselves can be included in the generic type , and use type parameters of generic types.

3. Generic methods can be included in both generic types and non-generic types.



Generic method declaration: as follows

public static int FunctionName(T value){...}



Overload of generic method:

public void Function1(T a );

public void Function1(U a);

This cannot constitute an overloading of a generic method. Because the compiler cannot determine whether the generic types T and U are different, it cannot determine whether the two methods are different



public void Function1(int x);

public void Function1(int x);

This can constitute an overload



public void Function1(T t) where T:A;

public void Function1(T t) where T:B;

This cannot constitute a generic method of overloading. Because the compiler cannot determine whether A and B in the constraints are different, it cannot determine whether the two methods are different.



Generic method rewriting:

In the process of rewriting, the abstract method in the abstract class constraints are inherited by default. As follows:

abstract class Base

{

public abstract T F(T t,U u) where U:T;

public abstract T G(T t) where T:IComparable ;

}



class MyClass:Base

{

  public override ) where T:IComparable{}

}

For the two overridden methods in MyClass

F method is legal, constraints are inherited by default

G method is illegal, specifying any constraints is redundant



Generic constraints:

1. C# generics require that any assumptions about "type parameters of all generic types or generic methods" must be based on "explicit constraints" to maintain the requirements required by C# Type safety.

2. "Explicit constraints" are expressed by where clauses, and you can specify four types of constraints: "base class constraints", "interface constraints", "constructor constraints", and "value type/reference type constraints".

3. "Explicit constraints" are not required. If "explicit constraints" are not specified, generic type parameters will only be able to access public methods in the System.Object type. For example: In the initial example, the obj member variable is defined. For example, we add a Test1 class to the initial example and define two public methods Func1 and Func2 in it, as shown below:






Let’s start analyzing these constraints:

Base class constraints:

class A

                                  public void Func1                               Func2()

                                                                                                                                                                              T//S’s variable can call the Func1 method

           s.Func1();

                //T’s variable can call the Func2 method

          t.Func2();

                             . }

Interface constraints:

interface IA <

}



interface IC

 {

T Func3();

}



class MyClass

where T : IA

where V : IB, IC

{

         public MyClass(T t, V v)

                                                                                                                                                   // The object of T can call Func1

             t.Func1();           v.Func2();

          v.Func3() );

}

}

Constructor constraint:

class A


                                                                                                                        ,,,,,,,,,,,,,,,,,,,,,,,,, )

                                                                                                                                             

                     public C()                                                                                                                                                                                                 ​



}



} l class d

{

public void func () {

c & lt; a & gt; c = new c & lt; a & gt; (); ; B & GT; ();}}}}

D Object Error: The Type B Must has have a public parameterless constructor in order to use it as Parameter 'in the GENERIC TYPE OR METHOD C & lt; t & gt;

Note: C# now only supports parameterless constructor constraints

At this time, since we have written a parameterized constructor for type B, the system will no longer automatically create a parameterless constructor for B, but if We add a parameterless constructor to type B, so the instantiation of object d will not report an error. The B type is defined as follows:

                                                     class B

{

                  public B()                                                                               Type/reference type:

public struct A { }

             public class B { }



             public class C where T : struct

                                                                                                    ;

                               C c2 = new C
The c2 object gets an error when compiling: 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'



Summary:

1. C#'s generic capabilities are supported by the CLR at runtime. It is different from the static templates supported by C++ at compile time, and also different from the simple "wiping method" supported by Java at the compiler level. of generics.

2. C#’s generic support includes four generic types: classes, structures, interfaces, delegates, and method members.

3. C#'s generics use the constraint method of "base class, interface, constructor, value type/reference type" to implement "explicit constraints" on type parameters. It does not support implicit signature-based constraints like C++ templates. formula constraints.

The above is the content of C# generic programming. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn