反射自定义类型返回 null
本文关键字:null 返回 类型 自定义 反射 | 更新日期: 2023-09-27 18:35:30
以下代码(在StackOverflow上找到)有效:
object ob = new { Name = "Erwin Okken", Age = 23, Position = new Point(2, 5) };
Type type = ob.GetType();
PropertyInfo pr = type.GetProperty("Name");
string value = pr.GetValue(ob, null).ToString(); // Erwin Okken
但是,如果我使用自己的类,它不起作用:
public class Subject
{
public string Name;
public int Age;
public Point Position;
public string Stringtest;
public int IntTest;
public Subject()
{
}
}
Type type = ob.GetType();
PropertyInfo pr = type.GetProperty("Name"); // null
string value = pr.GetValue(ob, null).ToString();
我尝试了所有绑定标志,但变量"pr"保持空。有人有想法吗?
你有这个:
public class Subject
{
public string Name;
...
}
在类型定义中,Name
字段而不是属性,则必须将类型更改为:
public class Subject
{
public string Name { get; set; }
...
}
另外,如果您想将Name
维护为字段(坏主意),您可以使用:
FieldInfo pr = type.GetField("Name");