Instantiate the image of the C # Generic Type

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.