Aspect Injector 文档——混入效果
Mixins is a powerfull feature that enables developers to add new logic/properties to an object by automatically implementing interfaces. Aspect containing a mixin will create members in target similar to interface's and proxy them back to the aspect.
Mixins 是一个功能强大的特性,它允许开发人员通过自动实现接口向对象添加新的逻辑/属性。包含 Mixin 的Aspect将在目标中创建接口中定义的成员,并将它们代理回aspect。
Consider scnerio where you want to add a property to a target:
思考一下向目标添加属性的场景:
1 public class Target 2 { 3 public void Do() {} 4 }
For this you need to create an interface that describes features you want to add:
为此,您需要创建一个声明您想要添加的元素的接口:
1 public interface IHaveProperty 2 { 3 string Data { get; set; } 4 }
then we will create an aspect:
然后我们将创建一个aspect:
1 [Aspect(Scope.Global)] 2 [Injection(typeof(MyAspect))] 3 [Mixin(typeof(IHaveProperty))] 4 public class MyAspect: Attribute, IHaveProperty 5 { 6 public string Data { get; set; } 7 }
And finally if apply this new aspect-attribute to Target
will make look like (after compilation):
最终,如果将这个新的[MyAspect]特性应用到 Target类,那么在编译之后,Target类看起来应该是这样的:
1 [MyAspect] 2 public class Target : IHaveProperty 3 { 4 string IHaveProperty.Data 5 { 6 get 7 { 8 return ((IHaveProperty)My1Aspect.__a$_instance).Data; 9 } 10 set 11 { 12 ((IHaveProperty)My1Aspect.__a$_instance).Data = value; 13 } 14 } 15 16 public void Do() 17 { 18 } 19 }
Note that it isn't necessary to apply aspect to Target
class itself, it is enough to apply it any member, like this:
注意,没有必要将[MyAspect]特性应用到 Target 类本身,只要将其应用到Target类的任意一个成员就足够了,如下所示:
1 public class Target 2 { 3 [MyAspect] 4 public void Do() {} 5 }
