Tim*_*Tim 3 c# reflection extension-methods
我正在尝试获取一个字典,其中包含具有必需属性的类中所有属性的 Property 和 DisplayName。
我正在尝试使用我拥有的扩展方法,但 PropertyDescriptor 不包含必需的定义。任何方向将不胜感激
public static Dictionary<string, string> GetDisplayNameList<T>()
{
var info = TypeDescriptor.GetProperties(typeof(T))
.Cast<PropertyDescriptor>()
.ToDictionary(p => p.Name, p => p.DisplayName);
return info;
}
Run Code Online (Sandbox Code Playgroud)
当然,您只需要检查该属性是否Required
定义了属性即可。您可以通过 访问此内容.Attributes
。例如:
public static Dictionary<string, string> GetDisplayNameList<T>()
{
var info = TypeDescriptor.GetProperties(typeof(T))
.Cast<PropertyDescriptor>()
.Where(p => p.Attributes.Cast<Attribute>().Any(a => a.GetType() == typeof(RequiredAttribute)))
.ToDictionary(p => p.Name, p => p.DisplayName);
return info;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2681 次 |
最近记录: |