如何读取类属性没有实例化?



我怎么能读取所有的类属性,没有这个类的实例化对象也没有硬编码类本身的名称?类的名称存储在一个字符串变量中。

string className = "myNamespace.myClass";
PropertyInfo[] myPropertyInfo;
try
{
myPropertyInfo = Type.GetType(className).GetProperties();
} catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}

总是返回

System.NullReferenceException: Object reference not set to an instance of an object.

我想避免像

这样的解决方案
switch(className) {
case "myNamespace.myClass":
myNamespace.myClass obj = new();
break;
case "myNamespace.anotherClass":
myNamespace.anotherClass obj = new();
break;
case "anotherNamespace.myClass":
anotherNamespace.myClass obj = new();
break;
}
myPropertyInfo = obj.GetType().GetProperties();

您的问题是Type.ToString()只返回没有限定符的类型(短)名称。在你的例子中,用"MyModel"代替"MyNamespace.MyModel, MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"。然而,Type.GetType()需要一个程序集限定的名称。否则它只返回null,因为没有找到类型。Type.GetType的字符串参数的文档:

要获取的类型的程序集限定名。看到AssemblyQualifiedName。类型是否在当前执行的在mscorlib.dll/System.Private.CoreLib.dll中,它是足以提供由其名称空间限定的类型名称。

不要用mod.GetType.ToString(),应该用mod.GetType.AssemblyQualifiedName

另一方面,当你已经有一个模型类的具体实例并调用GetType时,你永远不会得到null,因为每个对象都有一个类型。

最新更新