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;
}
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.
New In the constructor of the tester <t> classCodeActually, it is equivalent to the following code:
Public class tester <t>
Where T: New ()
{
Public Tester ()
{
T = system. activator. createinstance <t> ();
}
Private t;
}
That is to say, the reflection mechanism is still used to obtain instances of generic objects.