加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 获取属性描述属性

发布时间:2020-12-16 02:03:31 所属栏目:百科 来源:网络整理
导读:现有代码(简化) 我有这个功能 public static string[] GetFieldNamesT(IEnumerableT items) where T : class{ var properties = typeof(T).GetProperties().Where(p = SystemTypes.Contains(p.PropertyType)); // Only get System types return properties.S
现有代码(简化)

我有这个功能

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读