【问题标题】:How to loop through all the properties of a class?如何遍历一个类的所有属性?
【发布时间】:2010-10-06 14:14:26
【问题描述】:

我有课。

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

【问题讨论】:

    标签: .net vb.net class reflection properties


    【解决方案1】:

    使用反射:

    Type type = obj.GetType();
    PropertyInfo[] properties = type.GetProperties();
    
    foreach (PropertyInfo property in properties)
    {
        Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
    }
    

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

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

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

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

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

    【讨论】:

    • 顺便说一句,该 GetProperties 方法不应该有一些绑定标志吗?比如BindingFlags.Public | BindingFlags.GetProperty 什么的?
    • @Svish,你是对的 :) 它可以使用一些 BindingFlags,但它们是可选的。您可能想要公开 |实例。
    • 提示:如果你在处理静态字段,那么在这里简单地传递 null:property.GetValue(null);
    • 那么 obj.GetValue() 不再存在。当前在 c# 7 或 8 中迭代属性和检查值的方法是什么?我没有找到很多有效的方法。
    【解决方案2】:

    Brannon 给出的 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 会花很长时间 :)
    • 您可以随时使用自动转换器,网上有很多 :)
    • 是的,但不如手工编码。一个值得注意的是 Telerik 代码转换器
    • Telerik 的转换方式如下:gist.github.com/shmup/3f5abd617a525416fee7
    【解决方案3】:

    注意,如果你说的对象有自定义属性模型(比如DataRowViewDataTable),那么你需要使用TypeDescriptor;好消息是这仍然适用于普通课程(甚至可以是much quicker than reflection):

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

    【讨论】:

      【解决方案4】:

      反射很“重”

      也许试试这个解决方案:

      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 倍,如The Performance of Everyday Things 所示

      【讨论】:

        【解决方案5】:
        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);
                }
            }
        

        我使用上面的代码块来重置我的网络用户控件对象中的所有字符串属性,这些属性的名称以“Doc”开头。

        【讨论】:

          【解决方案6】:

          这是另一种方法,使用 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)}"))
          

          【讨论】:

            【解决方案7】:

            我就是这样做的。

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

            【讨论】:

            • 如果对象/类包含属性而不是字段,则使用 GetProperties() 而不是 GetFields()。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-07-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多