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


如果手头有DisplayName,如何以编程方式获取属性名“ ProviderFullName”?

最佳答案

您可以迭代属性和自定义属性-

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

关于c# - 如何使用DisplayName检索属性名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28278167/

10-12 12:43