Int*_*ude 5 .net c# 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; }
}
Run Code Online (Sandbox Code Playgroud)
我试过这样做:
var a = Attribute.GetCustomAttributes(typeof(StaffRosterEntry));
var attributeCount = a.Count();
Run Code Online (Sandbox Code Playgroud)
但是这次失败了.非常感谢您提供的任何帮助(链接到一些文档,或其他答案,或只是建议)!
小智 14
请使用以下代码:
Type type = typeof(YourClassName);
int NumberOfRecords = type.GetProperties().Length;
Run Code Online (Sandbox Code Playgroud)
由于属性位于属性上,因此您必须获取每个属性的属性:
Type type = typeof(StaffRosterEntry);
int attributeCount = 0;
foreach(PropertyInfo property in type.GetProperties())
{
attributeCount += property.GetCustomAttributes(false).Length;
}
Run Code Online (Sandbox Code Playgroud)