如何获取对象具有的属性数?

时间:2010-11-12 02:43:57

标签: c# .net attributes

我有一个包含许多属性的类,我需要找到一种方法来计算它拥有的属性数。我想这样做,因为类读取CSV文件,如果属性数(csvcolumns)小于文件中的列数,则需要进行特殊操作。以下是我班级的样本:

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

但是这次失败了。非常感谢您提供的任何帮助(链接到某些文档,或其他答案,或只是建议)!

4 个答案:

答案 0 :(得分:13)

请使用以下代码:

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

答案 1 :(得分:9)

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

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

答案 2 :(得分:0)

这是未经测试的,只是在我的头顶

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

答案 3 :(得分:0)

使用Reflection你有一个GetAttributes()方法,它将返回一个对象数组(属性)。

因此,如果你有一个对象的实例,那么使用obj.GetType()获取类型,然后你可以使用GetAttributes()方法。

相关问题