Get class by string value

前端 未结 5 901
感动是毒
感动是毒 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 14:41

    There are many good answers for your stated question. I would propose however, that you use a factory pattern for this type of requirement.

    Your 'factory' could be as simple as adding a static GetNewMyObject(string pattern) method to your base class as well as a protected static Dictionary. Then your derived classes could simply add their pattern + type to the factory (in a static constructor) allowing new derived classes to be added to the factory without modifying the base class.

    This way your 'pattern' strings do not have to match the type name and also you do not need to do any logical pattern matching as you can write:

    public static MyObject GetNewMyObject(string pattern)
    {
      return (MyObject)Activator.CreateInstance(StaticTypeDictionary[pattern]);
    }
    

提交回复
热议问题