【问题标题】:PostSharp: Custom attributes are removed when using OnMethodInvocationAspectPostSharp:使用 OnMethodInvocationAspect 时删除自定义属性
【发布时间】:2010-12-05 02:31:16
【问题描述】:

我有这样的一些方面:

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

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

【问题讨论】:

    标签: c# aop postsharp


    【解决方案1】:

    啊,我是这样解决的:

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

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

    【讨论】:

    • 感谢提问和回答 :)
    • 我有一个类似的问题,即从 PostSharp 相关类继承的属性在运行时不存在。想了解这里的底层机制为什么
    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多