. Net

Source: Internet
Author: User

In. Net, Microsoft provides us with many different methods for creating object instances, and their speeds are different. The following lists them one by one.

Use the new Keyword

This is the most common and fastest way in. Net:

1 var instance = new Class ();

 

Dynamic Creation using the CreateInstance method of the System. Activator class

Here, CreateInstance refers to the non-generic method of Activator:

1 var instance = System. Activator. CreateInstance (typeof (Class ));

 

Use the CreateInstance <T> method of the System. Activator class to dynamically create

Here, CreateInstance is the generic method of Activator:

1 var instance = System. Activator. CreateInstance <Class> ();

 

Use generic constraints and the new keyword to create an object (generic method)

First, you need to create a generic method:

1 public static T CreateInstance <T> () where T: new ()
2 {
3 return new T ();
4}

 

Here, the generic constraint where T: new () is used to ensure that the T type can be constructed with a no-argument constructor, so the new T () can be directly used in the code () to create objects:

1 var instance = CreateInstance <Class> ();

 

Use static methods of generic classes, generic constraints, and new keywords to create

Create a generic class first.

1 public static class StaticInitializer <T> where T: new ()
2 {
3 public static T CreateInstance ()
4 {
5 return new T ();
6}
7}

 

Then use the following code to create an instance:

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.