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調用沒有結果?獲取重寫屬性的屬性時的行爲不同?
按照這個例子有困難。 //不會發生什麼?定義了「ObsoleteAttribute」的方法? – 2012-02-19 22:32:38
所以要更清楚一點,看起來問題是在重寫的成員上找到定義的屬性。我假設你想要在繼承層次結構中的任何地方返回該成員上定義的屬性。 – Reddog 2012-02-19 22:35:20