【问题标题】:C# VS 2005: How to get a class's public member list during the runtime?C# VS 2005:如何在运行时获取类的公共成员列表?
【发布时间】:2010-09-25 06:49:07
【问题描述】:

我试图在运行时获取类成员变量列表。我知道这可能使用 typeof 和反射。但找不到一个例子。请有人为我解惑。

这是伪代码示例:

Class Test01
{ 
 public string str01;
 public string str02;
 public int myint01;
}

我想要这样的东西(伪代码):

Test01 tt = new Test01();
foreach(variable v in tt.PublicVariableList)
{
   debug.print v.name;
   debug.print v.type;
}

请帮我弄清楚如何在 C# VS2005 中做到这一点

非常感谢

【问题讨论】:

    标签: c# reflection typeof


    【解决方案1】:

    如果您需要公共字段,只需使用tt.GetType().GetFields()

    如果您需要其他成员,请使用GetProperties()GetMethods()GetEvents() 等获取特定成员,或者使用GetMembers() 获取所有成员。

    如果您想访问非公共成员,或将搜索限制为静态成员(或仅搜索实例成员),每个方法都有一个接受 BindingFlags 的重载。

    【讨论】:

      【解决方案2】:
      foreach (MemberInfo mi in tt.GetType().GetMembers()) ...
      

      【讨论】:

        猜你喜欢
        • 2013-12-13
        • 1970-01-01
        • 1970-01-01
        • 2010-11-07
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-16
        相关资源
        最近更新 更多