简体   繁体   中英

How to retrive Property Name using DisplayName?

public class DoctorInfo    
{
     [DisplayName("form1[0].P1[0].Physician-Name[0]")]
     public string ProviderFullName { get; set; }
}

How can i get Property Name "ProviderFullName" programmatically if i have its DisplayName in hand?

Given the DisplayName you can 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 .

If the DisplayName matches, then use the MemberInfo.Name property to get the name back.

you can iterate the properties and custom attributes -

 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;                        }
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM