Get class by string value

前端 未结 5 915
感动是毒
感动是毒 2021-02-18 14:11

I have an abstract class with a few derived class

public abstract class MyObject
{
    public string name { get; set; }
    public bool IsObject(string pattern);         


        
5条回答
  •  悲&欢浪女
    2021-02-18 15:02

    Yes, use Reflection.

    You can use Type.GetType to get an instance of the Type for the class by string, then instantiate it using Activator.CreateInstance, something like this:

    public MyObject Create(string pattern)
    {
        Type t = Type.GetType(pattern);
        if (t == null) {
            throw new Exception("Type " + pattern + " not found.");
        }
        return Activator.CreateInstance(t);
    }
    

    You could use Activator.CreateInstance(string, string) overload also, but this would not directly return a new instance of the Type required.

提交回复
热议问题