如何使用 DisplayName 检索 属性 名称?
How to retrive Property Name using DisplayName?
public class DoctorInfo
{
[DisplayName("form1[0].P1[0].Physician-Name[0]")]
public string ProviderFullName { get; set; }
}
如果我手头有 DisplayName,如何以编程方式获取 属性 名称 "ProviderFullName"?
鉴于 DisplayName
你可以 get all the PropertyInfo members in the class, then iterate over those to see if any of those has a DisplayName
attribute using MemberInfo.GetCustomAttributes.
如果 DisplayName
匹配,则使用 MemberInfo.Name
property 取回名称。
您可以迭代属性和自定义属性 -
PropertyInfo[] properties = typeof(DoctorInfo).GetProperties();
foreach (PropertyInfo prop in properties)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
DisplayNameAttribute displayName = attr as DisplayNameAttribute;
if (displayName != null)
{
var attributeName = displayName.DisplayName; // check if this matches what you want
string propertyName = prop.Name; }
}
}
public class DoctorInfo
{
[DisplayName("form1[0].P1[0].Physician-Name[0]")]
public string ProviderFullName { get; set; }
}
如果我手头有 DisplayName,如何以编程方式获取 属性 名称 "ProviderFullName"?
鉴于 DisplayName
你可以 get all the PropertyInfo members in the class, then iterate over those to see if any of those has a DisplayName
attribute using MemberInfo.GetCustomAttributes.
如果 DisplayName
匹配,则使用 MemberInfo.Name
property 取回名称。
您可以迭代属性和自定义属性 -
PropertyInfo[] properties = typeof(DoctorInfo).GetProperties();
foreach (PropertyInfo prop in properties)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
DisplayNameAttribute displayName = attr as DisplayNameAttribute;
if (displayName != null)
{
var attributeName = displayName.DisplayName; // check if this matches what you want
string propertyName = prop.Name; }
}
}