2009-10-08 27 views
11

當我有一些方面像這樣的自定義屬性被刪除:PostSharp:使用OnMethodInvocationAspect

public class MyAttribute : OnMethodInvocationAspect 
{ 
    public int Offset { get; internal set; } 

    public MyAttribute(int offset) 
    { 
     this.Offset = offset; 
    } 

    public override void OnInvocation(MethodInvocationEventArgs eventArgs) 
    { 
     //do some stuff 
    } 
} 

現在,我有我的課,我和我的屬性添加到它:

class MyClass 
{ 
    [MyAttribute(0x10)] 
    public int MyProp { get; set; } 
} 

工程一切正常。但現在我想用反射來獲得我的抵消;當我做

typeof(MyClass).GetProperty("MyProp").GetCustomAttributes(true); 

它什麼都沒有返回。我如何訪問我的原始偏移值(屬性屬性)?

回答

16

啊,我固定它是這樣的:

首先添加一個屬性喜歡你的屬性定義:

[MulticastAttributeUsage(MulticastTargets.Method, PersistMetaData=true)] 
public class MyAttribute : OnMethodInvocationAspect 

,然後我可以叫我的財產的get_方法來得到我想要的數據:

 foreach (PropertyInfo pi in typeof(T).GetProperties()) 
     { 
      var entityAttribute = (MyAttribute)(typeof(T).GetMethod("get_" + pi.Name).GetCustomAttributes(typeof(MyAttribute), true).FirstOrDefault()); 
     } 
+1

嗯不能接受我自己的答案了:-) –

+0

謝謝問題和答案:) –

+0

感謝的人。有一個類似的問題......它讓我困惑...... –