1
下面的代码(在计算器上找到)工作原理:反映自定义类型返回null
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();
我尝试了所有的BindingFlags ,但变量“pr”保持为空。任何人有想法?
'名称'是一个字段没有财产,ch把它改成属性'public string Name {get;组; }'或者使用'type.GetField'。 –
'ob'是什么意思? –
@Alessandro这是正确的答案(很可能),所以应该给出答案。 – Dialecticus