文章目錄
- 1. 使用特性直接訪問
- 2. 使用GetCustomAttribute()方法通過反射獲取
- 3. 使用LINQ查詢
- 總結和比較

在C#中,獲取屬性的displayName可以通過多種方式實現,包括使用特性、反射和LINQ。下面我將分別展示每種方法,并提供具體的示例代碼。
1. 使用特性直接訪問
在屬性定義時,可以使用DisplayName特性來指定屬性的顯示名稱。這種方式最簡單直接,適用于屬性在設計時就需要指定顯示名稱的情況。
using System;
using System.ComponentModel;public class MyModel
{[DisplayName("Full Name")]public string Name { get; set; }
}// 使用
MyModel model = new MyModel();
string displayName = model.Name.DisplayName; // 假設DisplayName特性已經被附加到屬性上
注意:在.NET Core中,DisplayName特性可能已經被棄用,你可能需要使用DisplayAttribute。
2. 使用GetCustomAttribute()方法通過反射獲取
通過反射,可以動態地獲取屬性上的自定義特性,包括DisplayAttribute。
using System;
using System.ComponentModel;
using System.Reflection;public class MyModel
{[Display(Name = "Full Name")]public string Name { get; set; }
}// 使用
MyModel model = new MyModel();
string displayName = "";PropertyInfo propertyInfo = model.GetType().GetProperty("Name");
DisplayAttribute displayAttribute = (DisplayAttribute)propertyInfo.GetCustomAttribute(typeof(DisplayAttribute), false);if (displayAttribute != null)
{displayName = displayAttribute.Name;
}
3. 使用LINQ查詢
如果你有一個屬性列表,并且想要查詢具有特定顯示名稱的屬性,可以使用LINQ來簡化查詢過程。
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;public class MyModel
{[Display(Name = "Full Name")]public string Name { get; set; }[Display(Name = "Date of Birth")]public DateTime DateOfBirth { get; set; }
}// 使用
MyModel model = new MyModel();
string displayName = "";var attributes = from property in model.GetType().GetProperties()let displayAttribute = Attribute.GetCustomAttribute(property, typeof(DisplayAttribute)) as DisplayAttributewhere displayAttribute != nullselect displayAttribute;foreach (var attribute in attributes)
{if (attribute.Name == "Full Name"){displayName = attribute.Name;break;}
}
總結和比較
1. 使用特性直接訪問: 最簡單的方式,只需在屬性上添加DisplayName特性。這種方式在屬性定義時就已經確定了顯示名稱,不需要在運行時進行額外的查詢。
2. 使用GetCustomAttribute()方法通過反射獲取: 通過反射獲取屬性上的DisplayAttribute特性。這種方式在運行時動態獲取屬性信息,更加靈活,但性能開銷比直接訪問特性稍大。
3. 使用LINQ查詢: 通過LINQ查詢屬性列表,找出具有特定顯示名稱的屬性。這種方式適合于有大量屬性時進行篩選,但可能過于復雜,對于簡單的場景不是最佳選擇。
每種方式都有其適用場景。在實際開發中,應根據具體需求和性能考量選擇最合適的方法。如果屬性較少,且在定義時就已知顯示名稱,使用特性是最簡單直接的方法。如果需要動態獲取屬性信息,或者屬性較多,使用反射或LINQ可能更合適。