如何获得对象具有的属性计数? [英] How do I get the count of attributes that an object has?

查看:88
本文介绍了如何获得对象具有的属性计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有许多属性的类,我需要找到一种方法来对它具有的属性数量进行计数.我要这样做是因为该类读取CSV文件,并且如果属性(csvcolumns)的数量小于文件中的列数,则需要进行特殊处理.这是我的班级示例:

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, and if the number of attributes (csvcolumns) is less than the number of columns in the file, special things will need to happen. Here is a sample 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; }
    }

我尝试这样做:

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

但这失败了.非常感谢您提供的任何帮助(指向某些文档的链接,其他答案或简单的建议)!

But this failed miserably. Any help you could give (links to some docs, or other answers, or simply suggestions) is greatly appreciated!

推荐答案

由于属性位于属性上,因此您必须获取每个属性的属性:

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

这篇关于如何获得对象具有的属性计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆