我想从字符串值开始获取对象的属性和方法。
我有一个表示类名的字符串值。
我这样做
string p = "Employee";
Type emp = Type.GetType(p);
object empObj = Activator.CreateInstance(emp);
但是对象是null,因为emp也是null ......有些不对劲
答案 0 :(得分:2)
使用反射时,必须使用完整的程序集名称或命名空间。
案例中的例子:
string p = "MyNamespace.Employee";
作为另一个例子,对于你将使用的System.Windows.Forms
类:
string p = "System.Windows.Forms.Form, " +
"System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " +
"PublicKeyToken=b77a5c561934e089");
查看更多内容,how to get class reference from string?
如果您不知道您的全名,可以使用AssemblyQualifiedName
property获取它。
Console.WriteLine(typeof(Employee).AssemblyQualifiedName);
答案 1 :(得分:1)
添加名称空间
string p = "Employee";
string namespace = "MyNamespace"
object empObj = Activator.CreateInstance(namespace, p);
或
string p = "Employee";
string namespace = "MyNamespace"
Type emp = Type.GetType(namespace + "." + p);
object empObj = Activator.CreateInstance(emp);
答案 2 :(得分:1)
Type.GetType(string)要求字符串参数为AssemblyQualifiedName。为了找到你想要创建的对象类型的构造函数,Activator类需要知道命名空间,包含它的程序集及其版本,以及对象本身类型的名称
例如:
string p = "MyNameSpace.Employee, MyAssembly, Version=1.4.1.0, Culture=neutral, PublicKeyToken=e7d6180f3b29ae11"
Type emp = Type.GetType(p);
object empObj = Activator.CreateInstance(emp);
如果您必须处理的类型范围很小且在编译时已知,那么最好使用简单的switch语句。或者,如果类型可能包含在其他程序集中,例如插件DLL,请查看MEF并使用Metadata修饰类,您可以从Factory对象访问这些类以构造正确类型的实例。