我想创建一个类的实例,使用一个字符串值。 根据我在这里阅读的内容:Activator.CreateInstance Method (String, String)它应该有效!
public class Foo
{
public string prop01 { get; set; }
public int prop02 { get; set; }
}
//var assName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var assName = System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName;
var foo = Activator.CreateInstance(assName, "Foo");
为什么这行不通? 我收到以下错误:
{"Could not load type 'Foo' from assembly 'theassemblyname, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.":"Foo"}
最佳答案
您应该使用完整的限定类型名称,而不是简单的类型名称,包括整个命名空间。
像这样:
var foo = Activator.CreateInstance(assName, "Bar.Baz.Foo");
作为MSDN说:
The fully qualified name of the preferred type.
关于c# - 基于字符串值创建实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41396373/