2013-04-12 2 views
-1

Так что, если у меня есть объект со свойством, как так:Как мне получить возвращаемые данные getter из атрибута/метаданных?

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

возможно, чтобы мой добытчик вернуть строку из свойства внутри атрибута? В этом конкретном случае MyCustomAttribute происходит от DisplayNameProperty, и я пытаюсь вернуть DisplayName

как бы это сделать ??

+0

Вы сказали, что 'MyCustomAttribute' происходит от' DisplayNameProperty', который запутан. Разве 'MyCustomAttribute' не нужно выводить из' ValidationAttribute' ??? –

+0

@ Давид Тансей, нет. – Sinaesthetic

ответ

3

Предположим, вы имеете в виду, что по какой-либо причине вы либо хотите вернуть атрибут DisplayNameAttribute из получателя, либо использовать его для чего-то в установщике.

Тогда это должно сделать это

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

Ваши вопросы не сформулированы достаточно четко, чтобы дать лучший ответ. Как говорят люди выше, сеттеры ничего не возвращают.

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"); 
     } 
    } 
} 
Смежные вопросы