【问题标题】:I can I map from a string to a constructor in C#?我可以从字符串映射到 C# 中的构造函数吗?
【发布时间】:2012-04-25 02:15:34
【问题描述】:

我有字符串输入,根据输入的值,我想调用特定对象的构造函数 (new Object1(int), new Object2(string), new Object3(int, int) 等都实现了 IObject 接口)。

而不是这样做链接 if/else 语句的明显(和缓慢)方式,我想做一些事情,比如有一个从字符串到构造函数的字典(例如 {"object1" -> new Object1 (int)})

有没有什么方法可以在 C# 中做这样的事情,也许是通过将“typeof”与构造函数结合起来?我想避免使用工厂,因为那需要并行代码结构,我想避免。

提前谢谢你

【问题讨论】:

  • 你想构造对象然后立即扔掉吗?
  • 使用 Type.GetConstructor() 获取 ConstructorInfo。使用它的 Invoke 方法来创建类型。或者使用 Activator.CreateInstance()。
  • 你认为一些 if 语句比创建一个虚假的对象实例要慢吗?
  • @DavidSchwartz:我绝对不想把它扔掉。我不是故意的。
  • @EdS:O(1) 语句链肯定会比单个 O(1) 语句慢。无论哪种方式,我的意思是代码更慢/更脏,并且可维护性更差。

标签: c# constructor


【解决方案1】:

你可以这样做:

var d = new Dictionary<string, Func<IObject>>();
d.Add("Object1", () => new Object1());
d.Add("Object2", () => new Object2());
d.Add("Object3", () => new Object3());
string typename = GetAStringFromSomewhere();
IObject foo = d[typename]();

【讨论】:

  • 简单,避免反射。
  • 看起来它应该完全符合我的要求。几个星期以来我一直想知道的随机问题:为什么最好使用“var d”而不是“Dictionary> d”?
  • 另外,我将如何调整它以便构造函数接受参数? (每个构造函数采用不同数量和类型的参数)
  • var d 是因为另一个太长而无法输入两次...您从哪里获得构造函数参数的值?如果它们是固定的,你可以直接在上面的代码中插入它们......
【解决方案2】:

通常的做法是使用Reflection

特别是Assembly.CreateInstance

【讨论】:

    【解决方案3】:

    如何定义一个静态方法来为您想要的每个类创建一个对象,然后使用字典映射字符串到静态生产者方法的委托类型?好吧,我知道这不是你想要的,但我现在不能评论你的问题。

    class Program
    {
        delegate object GetObjDelegate();
        static Dictionary<string, GetObjDelegate> Dic = new Dictionary<string, GetObjDelegate>();
    
        static void Main(string[] args)
        {
            Dic.Add("aaa", A.GetObj);
            Dic.Add("bbb", B.GetObj);
    
            object a = Dic["aaa"]();
            object b = Dic["bbb"]();
        }
    }
    
    class A
    {
        public A()
        {
        }
    
        public static A GetObj()
        {
            return new A();
        }
    }
    
    class B
    {
        public B()
        {
        }
    
        public static B GetObj()
        {
            return new B();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 2011-12-12
      相关资源
      最近更新 更多