现有代码(简化)
public static string[] GetFieldNames<T>(IEnumerable<T> items) where T : class { var properties = typeof(T).GetProperties().Where(p => SystemTypes.Contains(p.PropertyType)); // Only get System types return properties.Select(p => p.Name).ToArray(); }
所以如果说我有这门课
class MyClass { public string Name { get; set; } [Description("The value")] public int Value { get; set; } }
我可以有这样的代码
List<MyClass> items = ...; // Populate items somehow string[] fieldNames = GetFieldNames(items); // This returns ["Name","Value"]
这很好.
问题
我需要获取描述(如果存在),以便GetFieldNames(items)返回[“Name”,“The value”]
如何修改GetFieldNames()函数以读取Description属性(如果存在)?
(请注意,此功能已经简化,实际功能要复杂得多,所以请避免更改逻辑)
解决方法
这应该适合你:
return properties.Select(p => Attribute.IsDefined(p,typeof(DescriptionAttribute)) ? (Attribute.GetCustomAttribute(p,typeof(DescriptionAttribute)) as DescriptionAttribute).Description: p.Name ).ToArray();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。