以下代码(在 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();
我尝试了所有 Bindingflags,但变量“pr”保持为空。有人有想法吗?