如何让getter从属性/元数据返回数据
本文关键字:元数据 返回 数据 从属性 getter | 更新日期: 2023-09-27 18:09:08
如果我有一个对象的属性如下:
[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;
你的问题措辞不够清楚,不能给出一个更好的答案。如上所述,setter不返回任何东西。
我只是想把我的实际实现放在这里,希望它能帮助别人。如果你发现了不足或需要改进的地方,请告诉我。
// 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");
}
}
}