代码之家  ›  专栏  ›  技术社区  ›  Theofanis Pantelides

如何遍历C#类(.NET 2.0)的属性?

  •  3
  • Theofanis Pantelides  · 技术社区  · 14 年前

    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

    非常感谢。

    4 回复  |  直到 14 年前
        1
  •  9
  •   Håvard S    14 年前

    要遍历公共实例属性,请执行以下操作:

    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 对…的论点 GetProperties GetFields .

        2
  •  1
  •   Oded    14 年前

    您可以使用 reflection

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

        3
  •  1
  •   Rubens Farias    14 年前

    你可以使用它 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
  •  0
  •   Nitin Midha    14 年前

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

    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);
    }