C # How to Create a generic class T instance,

Source: Internet
Author: User

C # How to Create a generic class T instance,

Recently, I encountered a problem when writing a diploma base class: How to Create a generic class T instance?

I don't need to talk much about it. Let's go directly to the code. Currently we have found three methods: paste them first, and then summarize them. I hope to help my friends who have encountered the same problems.

 

Method 1: instantiate an instance passed in using an external method:

// Generic class: public class MySQLHelp <T> {private T; public MySQLHelp (t T) {this. t = t ;}}// Test class public class Test {public static void Main () {MySQLHelp <Message> mm = new MySQLHelp <Message> (new Message ());}} // other classes public class Message {}

Method 2: restrict the constructors of generic classes:

Restrict generic classes to be constructor with no parameters: public class MySQLHelp <T> where T: new ()

// Generic class: public class MySQLHelp <T> where T: new () {private T = new t (); public MySQLHelp () {}}// Test class public class Test {public static void Main () {MySQLHelp <Message> mm = new MySQLHelp <Message> ();}} // other classes public class Message {}

Method 3: Use the methods provided by Microsoft:

Use Microsoft's class:System. Activator(Contains methods for creating local or remote object types or obtaining referenced methods. Translation name: Activating Agent Class)

Create an instance of the specified type with the specified generic type parameter: System. Activator. CreateInstance <T> ()
// Generic class: public class MySQLHelp <T> {// create an instance of the type specified by the specified generic type parameter (using this method, you can not limit the generic type T, you do not need to add: where T: new () private T = System. activator. createInstance <T> (); public MySQLHelp () {}} // Test class public class Test {public static void Main () {MySQLHelp <Message> mm = new MySQLHelp <Message> () ;}// other public class Message {}

 

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.