如何用字符串定位对象的属性?

0 c# reflection properties object

我如何动态地引用Employee类型对象的属性?我喜欢什么employee."hasBeenPaid"?它涉及反思吗?

class Employee
{
    String name;
    Bool hasBeenPaid;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 5

你可以尝试:

Type type = your_class.GetType();
PropertyInfo propinfo = type.GetProperty("hasBeenPaid");
Run Code Online (Sandbox Code Playgroud)

如果你需要这个价值

value = propinfo.GetValue(your_class, null);
Run Code Online (Sandbox Code Playgroud)

  • 然后是propInfo.GetValue(your_object,null).此外,Type.GetProperty有几个参数(至少是BindingFlags),它允许您获取公共或非公共属性,静态或非静态(实例)等. (2认同)