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

3

假设我有一个类:

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

谢谢


1
请记住,“属性”这个词在这里是错误的。你应该说“迭代类的成员”。在C#中,“属性”有特定的含义。 - Sapph
我也常常感到疑惑。在UML中,用于类成员的术语“属性”肯定已经存在很长时间了。微软是否有意这样做,以混淆开发人员,作为某种“混淆和征服”的策略呢? - herzmeister
4个回答

9

遍历公共实例属性的方法如下:

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

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

2
+1 是因为你是唯一一个直接回答问题的人。 :P - Sapph

1

你可以使用反射

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

1

您可以使用反射来实现这一点。

这里有一篇文章,介绍如何通过反射来实现可扩展性。


0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接