.NET中的动态类初始化

rye*_*guy 4 c# reflection

假设我有基类FooParent,它有很多FooChildren.在运行时,我必须创建一个的实例FooChildren.我该怎么做?我意识到我可以创建一个巨大的地图(并使用代表)或一个巨大的switch/case声明,但这似乎有点草率.在像PHP这样的东西中,我可以像这样动态地创建一个类:

$className="FooClass";
$myNewFooClass=new $className; //makes a new instance of FooClass
Run Code Online (Sandbox Code Playgroud)

(你也可以使用反射来做到这一点).

.NET有这样的东西吗?反思是一种选择,它是否有任何性能损失?如果没有,我还有其他选择吗?

类的类型将由JSON请求确定.变量可以是我想要的任何东西.如果我想要枚举,它可以是整数,或者它可以是完整的类名.我还没有创造它所以我还没有决定.

Jon*_*eet 8

如果你真的想要,你可以用反射来做,但会有性能损失.它们是否重要将取决于您的具体情况.

根据您的具体要求,我可能会根据您的建议选择切换/案例陈述或地图.特别是,如果你需要根据你正在构造的类型将不同的参数传递给不同的构造函数,这将是有用的 - 通过反射做这件事会有点痛苦,因为你已经特殊 - 包装了不同的类型.


编辑:好的,所以我们现在知道总会有一个无参数的构造函数.在这种情况下,您的JSON可以轻松地包含没有命名空间的类名(如果它们都在同一名称空间中),并且您的方法可能如下所示:

public FooParent CreateFoo(string name)
{
    if (name == null)
    {
        throw new ArgumentNullException("name");
    }
    string fullName = "Some.NameSpace." + name;
    // This is assuming that the type will be in the same assembly
    // as the call. If that's not the case, we can look at that later.
    Type type = Type.GetType(fullName);
    if (type == null)
    {
        throw new ArgumentException("No such type: " + type);
    }
    if (!typeof(FooParent).IsAssignableFrom(type))
    {
        throw new ArgumentException("Type " + type +
                                    " is not compatible with FooParent.");
    }
    return (FooParent) Activator.CreateInstance(type);
}
Run Code Online (Sandbox Code Playgroud)

你在哪里确定要使用的名称?如果它在某处传递,那么当重新格式化一点时,switch语句可以非常简单:

public FooParent CreateFoo(string name)
{
    switch (name)
    {
        case "Foo1":      return new Foo1();
        case "Foo2":      return new Foo2();
        case "Foo3":      return new Foo3();
        case "Foo4":      return new Foo4();
        case "FooChild1": return new FooChild1();
        default:
            throw new ArgumentException("Unknown Foo class: " + name);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,刚写完之后我不确定它是否有任何真正的好处(除了性能)而不是使用Type.GetType(name)然后Activator.CreateInstance(type).

调用者如何知道要传入的类名?这绝对是动态的吗?你有没有机会使用泛型?你能告诉我们的情况越多,我们就越有帮助.