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 {}