Recently, I have been writing a set of development framework structures for main applications. Net 3.5 or above. A large number of generics are applied in this framework. The following describes how to instantiate a generic type. The code is used as an example, for example:
Public class
{
}
Public class B <T>
{
Public static T Get ()
{
// How can I instantiate the T object in this section? If default (T) is used, this cannot be used. Only one null value can be processed.
}
}
The above method is the most troublesome problem. It has always been assumed that default (T) can instantiate the T pair. Otherwise, this can only serve as a null value. If you want to solve the preceding problems, you can use either of the following methods:
1. Add a where T: new () after the generic class. The Code is as follows:
Public class
{
}
Public class B <T> where T: new ()
{
Public static T Get ()
{
T result = new T (); // You Can instantiate it. It can also be compiled.
...........
}
}
There may be a misunderstanding about the new () constraint that after the new constraint is used, it is consistent with the non-generic version when creating an object. 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, or instantiate an object.
2. You can use System. Activator. CreateInstance <T> () to create a wildcard instance. The Code is as follows:
Public class
{
}
Public class B <T>
{
Public static T Get ()
{
T s = System. Activator. CreateInstance <T> ();
.....
}
}
The two methods mentioned above use the reflection mechanism to obtain instances of generic objects.