问题 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);

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


11055
2017-10-08 18:17


起源



答案:


啊,我这样解决了:

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

[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());
        }

16
2017-10-08 18:28



嗯不能接受我自己的答案:-) - Jan Jongboom
谢谢你的问题和答案:) - Ivan Bianko
谢啦。有一个类似的问题......这让我感到困惑...... - Ev.
我有一个类似的问题,即从PostSharp相关类继承的属性在运行时不存在。想了解这里的潜在机制为什么 - Rob Nicholson


答案:


啊,我这样解决了:

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

[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());
        }

16
2017-10-08 18:28



嗯不能接受我自己的答案:-) - Jan Jongboom
谢谢你的问题和答案:) - Ivan Bianko
谢啦。有一个类似的问题......这让我感到困惑...... - Ev.
我有一个类似的问题,即从PostSharp相关类继承的属性在运行时不存在。想了解这里的潜在机制为什么 - Rob Nicholson