Creating an object from from an ID (or name)

前端 未结 5 1247
借酒劲吻你
借酒劲吻你 2020-12-21 10:09

I have an abstract class that a lot of child classes inherit:

  public abstract class CrawlerBase
    {
        public abstract void Process(string url);
            


        
5条回答
  •  甜味超标
    2020-12-21 10:46

    As Redi pointed out you do call call Process on any instance since all derive from the same base class. You still have some repetitive code in your switch case which can be simplified if you move away from a switch (if/else) to a mapping construct.

    Dictionary Types = new Dictionary
    {
        { "Trial", typeof(Trials) },
        { "Coverage", typeof(Coverage) },
    };
    
    void Crawl()
    {
        string itemType = "Trial";
        CrawlerBase crawler = (CrawlerBase)Activator.CreateInstance(Types[itemType]);
        crawler.Process("url");
    }
    

    You can do it also with delegates like Dennis if you put a factory method as value into your dictionary.

提交回复
热议问题