[英]How do I have my getter return data from attribute/metadata?
因此,如果我有一個具有如下屬性的對象:
[MyCustomAttribute("somevalue")]
public string PropertyName { get; set; }
是否有可能讓我的getter從屬性內的屬性返回一個字符串? 在這種情況下, MyCustomAttribute
派生自DisplayNameProperty
而我試圖返回DisplayName
我該怎么做?
讓我們假設您的意思是出於某種原因,您要么想要從getter返回DisplayNameAttribute,要么將其用於setter中的某些東西。
那應該做
MemberInfo property = typeof(YourClass).GetProperty("PropertyName");
var attribute = property.GetCustomAttributes(typeof(MyCustomAttribute), true)
.Cast<MyCustomAttribute>.Single();
string displayName = attribute.DisplayName;
您的問題措辭不夠清晰,無法給出更好的答案。 正如人們在上面所說的那樣,安裝員不會返回任何東西。
我只是想將我的實際實現放在這里,因此希望能對某人有所幫助。 萊姆知道您是否發現不足或需要改進的地方。
// Custom attribute might be something like this
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class BrandedAttribute : Attribute
{
private readonly ResourceManager _rm;
private readonly string _key;
public BrandedAttribute(string resourceKey)
{
_rm = new ResourceManager("brand", typeof(BrandedAttribute).Assembly);
_key = resourceKey;
}
public override string BrandText
{
get
{
// do what you need to do in order to generate the right text
return brandA_resource.ResourceManager.GetString(_key);
}
}
public override string ToString()
{
return DisplayName;
}
}
// extension
public static string AttributeToString<T>(this object obj, string propertyName)
where T: Attribute
{
MemberInfo property = obj.GetType().GetProperty(propertyName);
var attribute = default(T);
if (property != null)
{
attribute = property.GetCustomAttributes(typeof(T), true)
.Cast<T>().Single();
}
// I chose to do this via ToString() just for simplicity sake
return attribute == null ? string.Empty : attribute.ToString();
}
// usage
public MyClass
{
[MyCustom]
public string MyProperty
{
get
{
return this.AttributeToString<MyCustomAttribute>("MyProperty");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.