How do I get the count of attributes that an object has?

后端 未结 4 1678
慢半拍i
慢半拍i 2021-02-06 07:07

I\'ve got a class with a number of attributes, and I need to find a way to get a count of the number of attributes it has. I want to do this because the class reads a CSV file,

相关标签:
4条回答
  • 2021-02-06 07:25

    Using Reflection you have a GetAttributes() method that will return an array of object (the attributes).

    So if you have an instance of the object then get the type using obj.GetType() and then you can use the GetAttributes() method.

    0 讨论(0)
  • 2021-02-06 07:30

    Since the attributes are on the properties, you would have to get the attributes on each property:

    Type type = typeof(StaffRosterEntry);
    int attributeCount = 0;
    foreach(PropertyInfo property in type.GetProperties())
    {
     attributeCount += property.GetCustomAttributes(false).Length;
    }
    
    0 讨论(0)
  • 2021-02-06 07:32

    Please use the following code:

    Type type = typeof(YourClassName);
    int NumberOfRecords = type.GetProperties().Length;
    
    0 讨论(0)
  • 2021-02-06 07:35

    This is untested and just off the top of my head

    System.Reflection.MemberInfo info = typeof(StaffRosterEntry);
    object[] attributes = info.GetCustomAttributes(true);
    var attributeCount = attributes.Count(); 
    
    0 讨论(0)
提交回复
热议问题