如何遍历一个类的所有属性?


168

我有课

Public Class Foo
    Private _Name As String
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _Age As String
    Public Property Age() As String
        Get
            Return _Age
        End Get
        Set(ByVal value As String)
            _Age = value
        End Set
    End Property

    Private _ContactNumber As String
    Public Property ContactNumber() As String
        Get
            Return _ContactNumber
        End Get
        Set(ByVal value As String)
            _ContactNumber = value
        End Set
    End Property


End Class

我想遍历以上类的属性。例如;

Public Sub DisplayAll(ByVal Someobject As Foo)
    For Each _Property As something In Someobject.Properties
        Console.WriteLine(_Property.Name & "=" & _Property.value)
    Next
End Sub

Answers:


297

使用反射:

Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}

对于Excel-由于列表中没有“ System.Reflection”条目,因此必须添加哪些工具/参考项才能访问BindingFlags

编辑:您也可以将BindingFlags值指定为type.GetProperties()

BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);

这会将返回的属性限制为公共实例属性(不包括静态属性,受保护的属性等)。

您无需指定BindingFlags.GetProperty,可以在调用时使用它type.InvokeMember()来获取属性的值。


顺便说一句,那个GetProperties方法不应该有一些绑定标志吗?喜欢BindingFlags.Public | BindingFlags.GetProperty还是什么?
Svish

@Svish,您是对的:)它可以使用一些BindingFlags,但它们是可选的。您可能需要“公共” | 实例。
布兰农

提示:如果要处理静态字段,则只需在此处传递null:property.GetValue(null);
alansiqueira27年

42

请注意,如果您要讨论的对象具有自定义属性模型(例如的DataRowViewfor DataTable),则需要使用TypeDescriptor; 好消息是,这对于常规课程仍然可以正常使用(甚至可以比反射更快):

foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
    Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}

这也使您可以轻松访问诸如TypeConverter格式化之类的内容:

    string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));

32

布兰农给出的C#的VB版本:

Public Sub DisplayAll(ByVal Someobject As Foo)
    Dim _type As Type = Someobject.GetType()
    Dim properties() As PropertyInfo = _type.GetProperties()  'line 3
    For Each _property As PropertyInfo In properties
        Console.WriteLine("Name: " + _property.Name + ", Value: " + _property.GetValue(Someobject, Nothing))
    Next
End Sub

使用绑定标志代替第3行

    Dim flags As BindingFlags = BindingFlags.Public Or BindingFlags.Instance
    Dim properties() As PropertyInfo = _type.GetProperties(flags)

谢谢,转换到VB花费了我很长时间:)
Brannon

您可以随时使用自动转换器,网络上有很多:)
balexandre 2009年

1
是的,但不如手工编码那么好。一个著名的例子是telerik代码转换器
Sachin Chavan

这就是Telerik的转换方式:gist.github.com/shmup/3f5abd617a525416fee7
shmup

7

反射相当“沉重”

也许尝试以下解决方案:// C#

if (item is IEnumerable) {
    foreach (object o in item as IEnumerable) {
            //do function
    }
} else {
    foreach (System.Reflection.PropertyInfo p in obj.GetType().GetProperties())      {
        if (p.CanRead) {
            Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj,  null)); //possible function
        }
    }
}

'VB.Net

  If TypeOf item Is IEnumerable Then

    For Each o As Object In TryCast(item, IEnumerable)
               'Do Function
     Next
  Else
    For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
         If p.CanRead Then
               Console.WriteLine("{0}: {1}", p.Name, p.GetValue(obj, Nothing))  'possible function
          End If
      Next
  End If

反射会减慢方法调用速度的+/- 1000倍,如《日常事物的性能》中所示


2

这是使用LINQ lambda的另一种方法:

C#:

SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));

VB.NET:

SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))

1

这就是我的方法。

foreach (var fi in typeof(CustomRoles).GetFields())
{
    var propertyName = fi.Name;
}

1
如果对象/类包含属性而不是字段,请使用GetProperties()而不是GetFields()。
GarDavis

0
private void ResetAllProperties()
    {
        Type type = this.GetType();
        PropertyInfo[] properties = (from c in type.GetProperties()
                                     where c.Name.StartsWith("Doc")
                                     select c).ToArray();
        foreach (PropertyInfo item in properties)
        {
            if (item.PropertyType.FullName == "System.String")
                item.SetValue(this, "", null);
        }
    }

我使用了上面的代码块来重置Web用户控件对象中所有以“ Doc”开头的字符串属性。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.