【问题标题】:How do I get the count of attributes that an object has?如何获取对象具有的属性计数?
【发布时间】:2010-11-12 02:43:57
【问题描述】:

我有一个具有许多属性的类,我需要找到一种方法来计算它具有的属性数量。我想这样做是因为该类读取一个 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();

但这惨遭失败。非常感谢您提供的任何帮助(一些文档的链接、其他答案或简单的建议)!

【问题讨论】:

    标签: c# .net attributes


    【解决方案1】:

    请使用以下代码:

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

    【讨论】:

    【解决方案2】:

    这是未经测试的,就在我的脑海中

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 查看here 以了解如何使用GetAttributes() 的示例。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-30
        • 2012-04-18
        • 1970-01-01
        • 2019-05-20
        • 2020-10-25
        • 2012-01-28
        • 1970-01-01
        相关资源
        最近更新 更多