如何让getter从属性/元数据返回数据?

时间:2013-04-12 20:29:51

标签: c# .net asp.net-mvc-4 attributes

所以如果我有一个像这样的属性的对象:

[MyCustomAttribute("somevalue")]
public string PropertyName { get; set; }

是否可以让我的getter从属性内的属性返回一个字符串?在这种特殊情况下,MyCustomAttribute来自DisplayNameProperty而我正在尝试返回DisplayName

我该怎么做?

2 个答案:

答案 0 :(得分:3)

我们假设您的意思是出于某种原因,您要么从getter返回DisplayNameAttribute,要么将其用于setter中的某些内容。

然后这应该做到

MemberInfo property = typeof(YourClass).GetProperty("PropertyName");   
var attribute = property.GetCustomAttributes(typeof(MyCustomAttribute), true)
      .Cast<MyCustomAttribute>.Single();
string displayName = attribute.DisplayName;

您的问题没有明确表达,无法给出更好的答案。正如人们上面说的那样 - 制定者不会返回任何东西。

答案 1 :(得分:1)

我只是想把我的实际实现放在这里,所以它希望有助于某人。 Lemme知道你是否有缺陷或需要改进的地方。

// 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");
        }
    }
}