2012-02-19 66 views
0
using System; 

class Program 
{ 
    static void Main() 
    { 
     var p = typeof(MyClass2).GetProperty("Value"); 
     var a = Attribute.GetCustomAttribute(p, typeof(ObsoleteAttribute), true); 
     Console.WriteLine(a != null); 
    } 
} 

public class MyClass 
{ 
    [CommandProperty()] 
    public virtual string Value { get; set; } 
} 

public class MyClass2 : MyClass 
{ 
    public override string Value { get; set; } 
} 

[AttributeUsage(AttributeTargets.Property, Inherited = true)] 
public class CommandPropertyAttribute : Attribute 
{ 
/* ... */ 
} 

PropertyInfo prop = ***The PropertyInfo of MyClass2.Value***; 
object[] attrs = prop.GetCustomAttributes(typeofCPA, true); 
Attribute at =Attribute.GetCustomAttribute(prop, typeofCPA, true); 
if (attrs.Length == 0 && at != null) 
{ 
    // Yes this happens.   
} 

爲什麼我從第一次GetCustomAttributes調用沒有結果?獲取重寫屬性的屬性時的行爲不同?

+0

按照這個例子有困難。 //不會發生什麼?定義了「ObsoleteAttribute」的方法? – 2012-02-19 22:32:38

+0

所以要更清楚一點,看起來問題是在重寫的成員上找到定義的屬性。我假設你想要在繼承層次結構中的任何地方返回該成員上定義的屬性。 – Reddog 2012-02-19 22:35:20

回答

2

documentation for MemberInfo.GetCustomAttributes(繼承PropertyInfo)的狀態;

此方法忽略屬性和事件的繼承參數。 要在繼承鏈中搜索屬性和 事件的屬性,請使用Attribute.GetCustomAttributes方法的相應超載。

換句話說,(設計錯誤)行爲。

+0

此外,我發現此: 繼承 - 類型:System.Boolean - 真正的搜索此成員的繼承鏈來查找屬性;否則,是錯誤的。 **該屬性和事件被忽略;見備註** - 謝謝 – Tarion 2012-02-20 12:05:50