首页 文章

如何遍历类的所有属性?

提问于
浏览
156

我上课了 .

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

7 回答

  • 1

    我就是这样做的 .

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

    这是使用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)}"))
    
  • 39

    请注意,如果您正在谈论的对象具有自定义属性模型(例如 DataTableDataRowView 等),则需要使用 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));
    
  • 1

    使用反射:

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

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

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

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

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

  • 30

    Brannon给出的VB版C#:

    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)
    
  • 281

    反思非常“沉重”

    也许尝试这个解决方案:// 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 x方法调用的速度,如The Performance of Everyday Things所示

  • 1
    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”开头 .

相关问题