2015-10-06 28 views
1

我创建了一个继承LocationInterceptionAspect的属性。 出于演示的目的,代码如下:PostSharp LocationInterceptionAspect不适用于继承的属性

[Serializable] 
public class RepeaterAttribute : LocationInterceptionAspect 
{ 
    public override bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo) 
    { 
     var propertyInfo = locationInfo.PropertyInfo; 
     if (propertyInfo == null) return false; 
     if (propertyInfo.PropertyType != typeof(String)) 
      return false; 
     return base.CompileTimeValidate(locationInfo); 
    } 
    public override void OnSetValue(LocationInterceptionArgs args) 
    { 
     args.Value = ((String)args.Value) + ((String)args.Value); 
     args.ProceedSetValue(); 
    } 
} 

我有一个名为外部库,并在其中一个叫父类。

namespace External 
{ 
    public class Parent 
    { 
     public String ParentProperty { get; set; } 
    } 
} 

在控制台应用程序中,我有一个名为Child的类从Parent继承。 控制台应用程序引用外部库。

public class Child : External.Parent 
{ 
    public String ChildProperty { get; set; } 
} 

在我的控制台应用程序中,我的代码是。

namespace ConsoleApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var child = new Child(); 
      child.ParentProperty = "A"; 
      Console.WriteLine("This should be 'AA' : '{0}'", child.ParentProperty); 
      child.ChildProperty = "B"; 
      Console.WriteLine("This should be 'BB' : '{0}'", child.ChildProperty); 
      Console.ReadKey(); 
     } 
    } 
} 

,并在控制台应用程序的AssemblyInfo.cs我:

[assembly: ConsoleApplication.Repeater(AttributeTargetTypes = "ConsoleApplication.Child")] 

但是当我运行的中继器的属性没有被应用到从父类继承的“ParentProperty”。

回答

0

PostSharp无法更改正在转换的组件中的类。基本属性在不同的程序集中声明。这是LocationInterceptionAspect的限制。

您可以使用MethodInterception,它支持不同的组件拦截方法:

[Serializable] 
public class SetterRepeaterAttribute : MethodInterceptionAspect 
{ 
    public override void OnInvoke(MethodInterceptionArgs args) 
    { 
     args.Arguments[0] = ((String)args.Arguments[0]) + ((String)args.Arguments[0]); 
     args.Proceed(); 
    } 
} 

和组播它装配水平基类的setter方法:

[assembly: ConsoleApplication2.SetterRepeater(
    AttributeTargetMembers = "set_ParentProperty", 
    AttributeTargetTypes = "External.Parent", 
    AttributeTargetAssemblies = "regex:.*")] 

注意,在这种情况下,拦截是在调用站点级别完成的,ParentProperty设置器不会自行更改。来自原始程序集的调用不会被拦截。