我可以使用反射来查找多播产生的方面吗?

时间:2015-11-12 13:59:37

标签: postsharp

我有一个案例,其中A类的方面CanBeDependedUpon被多播到类A的属性。但是当从方面DependsOn检查类A时,我没有在Y的属性上找到CanBeDependedUpon。这是正确的PostSharp行为吗? / p>

[CanBeDependedUpon]
class A
{
    public bool Foo
    {
        get;
        set;
    }

    [DependsOn("Foo")]
    public bool Bar
    {
        get;
        set;
    }
}

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property, AllowMultiple = true)]
[MulticastAttributeUsage(MulticastTargets.Class | MulticastTargets.Struct | MulticastTargets.Property, PersistMetaData = true, AllowMultiple = true)]
class CanBeDependedUpon : Aspect
{
}

class DependsOn : Aspect
{
    private string _target;

    public DependsOn(string target)
    {
        _target = target;
    }

    public override bool CompileTimeValidate(object target)
    {
        //validate that the target property exists and is annotated with X.
        return base.CompileTimeValidate(target);
    }
}

1 个答案:

答案 0 :(得分:1)

默认情况下,一旦将方面应用于您的代码,PostSharp就会删除该属性。如果要使用反射查找属性,可以明确指示PostSharp保留属性。

为此,您需要将MulticastAttributeUsage属性应用于您的班级,并将PersistMetaData设置为true

[MulticastAttributeUsage( MulticastTargets.Class, PersistMetaData = true )]

此用例在此处记录:http://doc.postsharp.net/multicast-reflection