简体   繁体   中英

Initialize generic class by string

I have a string "MyClass". Is there any way to initialize a generic object by string?

public void LoadToCache<T>(string key) where T : class, new()
{
  //string key is a class name like "MyClass"
    using (var bl = new BusinessLayer<key>())
    {
       bl.GetAll();
    }
} 
//---------------------------------------------------------------
public class BusinessLayer<T> where T : class
{
  ..
  ..
}
//---------------------------------------------------------------
public class MyClass
{
  ..
  ..
}

You could get the types from your assembly by reflection and create a instance using Activator.CreateInstance .

I Hope this helps:

My class:

public class Car
{

}

The method:

string myClass = "Car";
var types = Assembly.GetExecutingAssembly().GetTypes().ToList();
var myType = types.FirstOrDefault(i => i.IsClass && i.Name == myClass);
var instance  = Activator.CreateInstance((Type) myType);

Console.Write(instance.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM