How to get the number of attributes that an object has?

I have a class with a number of attributes, and I need to find a way to count the number of its attributes. I want to do this because the class reads the CSV file, and if the number of attributes (csvcolumns) is less than the number of columns in the file, special things must happen. Here is an example of what my class looks like:

    public class StaffRosterEntry : RosterEntry
    {
        [CsvColumn(FieldIndex = 0, Name = "Role")]
        public string Role { get; set; }

        [CsvColumn(FieldIndex = 1, Name = "SchoolID")]
        public string SchoolID { get; set; }

        [CsvColumn(FieldIndex = 2, Name = "StaffID")]
        public string StaffID { get; set; }
    }

I tried to do this:

var a = Attribute.GetCustomAttributes(typeof(StaffRosterEntry));
var attributeCount = a.Count();

But it failed. Any help you could give (links to some documents or other answers or just suggestions) is greatly appreciated!

+3
source share
4 answers

Since attributes are in properties, you will need to get the attributes for each property:

Type type = typeof(StaffRosterEntry);
int attributeCount = 0;
foreach(PropertyInfo property in type.GetProperties())
{
 attributeCount += property.GetCustomAttributes(false).Length;
}
+7

, :

Type type = typeof(YourClassName);
int NumberOfRecords = type.GetProperties().Length;
+8

This is untested and very close to my head

System.Reflection.MemberInfo info = typeof(StaffRosterEntry);
object[] attributes = info.GetCustomAttributes(true);
var attributeCount = attributes.Count(); 
0
source

With Reflection, you have a GetAttributes () method that will return an array of an object (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
source

Source: https://habr.com/ru/post/1774434/


All Articles