gpt4 book ai didi

c# - Activator.CreateInstance 失败

转载 作者:太空狗 更新时间:2023-10-29 22:27:51 25 4
gpt4 key购买 nike

我正在使用 Activator.CreateInstance 动态创建一个实例。但是,它说对象在每次尝试时都不能为空。粘贴下面的代码。我做错了什么吗?

有什么问题吗

Activator.CreateInstance

取代传统的 switch/case 语句来确定运行时的对象类型?谢谢。

public abstract  class Base
{
public abstract void Func();

}
public class Derived:Base
{
public override void Func()
{
MessageBox.Show("Derived First");
}
}

public class Derived2 : Base
{
public override void Func()
{
MessageBox.Show("Derived Second");
}
}

private void button1_Click(object sender, EventArgs e)
{
// I was trying to make use of the overladed version
// where it takes the Type as parameter.
BaseClass report =
(BaseClass) Activator.CreateInstance(Type.GetType("Derived"));
report.Func();
}

最佳答案

来自 Type.GetTypetypeName 参数的文档:

The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

这意味着您(至少)还需要传递命名空间:

BaseClass report = (BaseClass) Activator.CreateInstance(Type.GetType("YourNamespace.Derived")); 

关于c# - Activator.CreateInstance 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8969268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com