Get class by string value

前端 未结 5 927
感动是毒
感动是毒 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条回答
  •  猫巷女王i
    2021-02-18 14:44

    As Rudi Visser told, you should use reflection.

    Also to get your class name you should not hardcode it. If you whant to use your name property just write

    public abstract class MyObject
    {
        public string name 
        { 
            get
            {
                return this.GetType().Name;
            }
        }
        public bool IsObject(string pattern);
        ...
    }
    

    if you don't have the name of class, just some string that represent it, than you could check all the classes derived from MyObject

    public MyObject Create(string pattern)
    {
        Type[] types = Assembly.GetExecutingAssembly().GetTypes();
        foreach (Type type in types.Where(t => t.IsSubclassOf(typeof(MyObject))))
        {
            MyObject obj = (MyObject)Activator.CreateInstance(type);
            if (obj.name == pattern)
            {
                return obj;
            }
        }
        throw new Exception("Type " + pattern + " not found.");
    }
    

提交回复
热议问题