11

我有这样的一些方面:

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

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

4

1 回答 1

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());
        }
于 2009-10-08T18:28:25.273 回答