PostSharp:使用OnMethodInvocationAspect时会删除自定义属性

Jan*_*oom 11 c# aop postsharp

我有一些像这样的方面:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我正在上课,我将其属性添加到它:

class MyClass
{
    [MyAttribute(0x10)]
    public int MyProp { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

一切正常.然而现在我想用反射来获得我的偏移; 当我做

typeof(MyClass).GetProperty("MyProp").GetCustomAttributes(true);
Run Code Online (Sandbox Code Playgroud)

它什么都不返回.如何访问原始偏移值(属性上的属性)?

Jan*_*oom 16

啊,我这样解决了:

首先在属性定义中添加一个属性,如:

[MulticastAttributeUsage(MulticastTargets.Method, PersistMetaData=true)]
public class MyAttribute : OnMethodInvocationAspect
Run Code Online (Sandbox Code Playgroud)

然后我可以调用我的属性的get_方法来获取我想要的数据:

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