There may be a misunderstanding about the new () constraint that after the new constraint is used, the object creation is consistent with the non-generic version:
Public class Tester <T> Where T: new () { Public Tester () { T = new T (); // is equivalent to a non-generic version of new? For example, object o = new object ();? }
Private T t;
} |
In fact, the function of using the new keyword is to let the compiler check whether the bound generic parameter has a non-argument constructor in the case of generics instantiation:
Tester <SomeType> t = new Tester <SomeType> (); // The Compiler checks whether SomeType has a non-argument constructor. If not, compile error occurs. |
The new code in the constructor of the Tester <T> class is actually equivalent to the following code:
Public class Tester <T> Where T: new () { Public Tester () { T = System. Activator. CreateInstance <T> (); }
Private T t;
} |
That is to say, the reflection mechanism is still used to obtain instances of generic objects.