【问题标题】:How do I iterate through the Attributes of a C# class (.NET 2.0)?如何遍历 C# 类 (.NET 2.0) 的属性?
【发布时间】:2010-02-05 09:23:55
【问题描述】:

假设我有一堂课:

public class TestClass
{
  public String Str1;
  public String Str2;
  private String Str3;

  public String Str4 { get { return Str3; } }

  public TestClass()
  {
    Str1 = Str2 = Str 3 = "Test String";
  }
}

有没有办法(C# .NET 2)遍历“TestClass”类并打印出公共变量和属性?

记住 .Net2

谢谢

【问题讨论】:

  • 请记住,这里的“属性”是错误的词。您可能应该说“遍历一个类的成员”。 “属性”在 C# 中具有特定含义。
  • 我也经常想知道。 UML 中用于类成员的术语“属性”肯定已经存在了很长时间。微软是否故意做这些事情,以迷惑开发者作为某种“迷惑和征服”策略?

标签: c# asp.net json class .net-2.0


【解决方案1】:

遍历公共实例属性:

Type classType = typeof(TestClass);
foreach(PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
  Console.WriteLine(property.Name);
}

遍历公共实例字段:

Type classType = typeof(TestClass);
foreach(FieldInfo field in classType.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
  Console.WriteLine(field.Name);
}

如果您还想包含非公共属性,请将BindingFlags.NonPublic 添加到GetPropertiesGetFields 的参数中。

【讨论】:

  • +1 是唯一直接直接回答问题的人。 :P
  • 这正是我所需要的!谢谢
【解决方案2】:

您可以使用reflection 执行此操作。

这里是an article,它使用反射来实现可扩展性。

【讨论】:

    【解决方案3】:

    您可以使用reflection

    TestClass sample = new TestClass();
    BindingFlags flags = BindingFlags.Instance | 
        BindingFlags.Public | BindingFlags.NonPublic;
    
    foreach (FieldInfo f in sample.GetType().GetFields(flags))
        Console.WriteLine("{0} = {1}", f.Name, f.GetValue(sample));
    
    foreach (PropertyInfo p in sample.GetType().GetProperties(flags))
        Console.WriteLine("{0} = {1}", p.Name, p.GetValue(sample, null));
    

    【讨论】:

      【解决方案4】:

      要获取我们将使用的类型的属性:

      Type classType = typeof(TestClass);
          PropertyInfo[] properties = classType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
      

      要获得定义的类的属性,我们将使用:

      Type classType = typeof(TestClass);
      object[] attributes = classType.GetCustomAttributes(false); 
      

      传递的布尔标志为继承标志,是否在继承链中搜索。

      要获取我们将使用的属性的属性:

      propertyInfo.GetCustomAttributes(false); 
      

      使用上面给出的哈佛代码:

      Type classType = typeof(TestClass);
      object[] classAttributes = classType.GetCustomAttributes(false); 
      foreach(PropertyInfo property in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
      {
        object[] propertyAttributes = property.GetCustomAttributes(false); 
        Console.WriteLine(property.Name);
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-30
        • 2012-10-29
        • 1970-01-01
        • 2010-10-17
        • 2010-10-26
        • 2012-07-05
        • 2011-11-26
        • 2021-09-24
        • 1970-01-01
        相关资源
        最近更新 更多