gpt4 book ai didi

c# - 使用 PostSharp 在 C# 中面向方面的设计模式 Cuckoo's Egg

转载 作者:太空宇宙 更新时间:2023-11-03 16:04:05 24 4
gpt4 key购买 nike

我正在尝试使用 Postsharp 在 C# 中实现 AO 设计模式 Cuckoo's egg。

这个设计模式的想法正如它的名称所述,用其他对象替换现有对象。在 AspectJ 中,它是通过这样的方式完成的:

public aspect MyClassSwapper {
public pointcut myConstructors(): call(MyClass.new());
Object around(): myConstructors() {
return new AnotherClass();
}
}

public class AnotherClass extends MyClass {
. . .
}

我是 Postsharp 的新手,所以我想问一下,Postsharp 中是否有工具可以做类似的事情 - 覆盖基类构造函数的返回值并返回子类的对象?

最佳答案

PostSharp 允许您申请 OnMethodBoundaryAspect对于构造函数,您仍然无法替换返回的对象实例。事实上,C# 中的构造函数不返回值。有相关问题herehere .

另一种实现布谷鸟蛋模式的方法是截取原始类的方法,而是在另一个类实例上调用适当的方法。在这种情况下,AnotherClass 甚至不必从 MyClass 派生,或者您可以将不同的方法委托(delegate)给不同的替换类。

MethodInterceptionAspect 的示例实现实现该模式可能如下所示:

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method, Inheritance = MulticastInheritance.None)]
public class MyClassSwapperAttribute : MethodInterceptionAspect, IInstanceScopedAspect
{
private readonly Type cuckooType;

[NonSerialized] private object cuckooEgg;

public MyClassSwapperAttribute(Type cuckooType)
{
this.cuckooType = cuckooType;
}

private MyClassSwapperAttribute()
{
// this creates an "empty" aspect instance applied on the cuckoo's egg itself
}

public object CreateInstance(AdviceArgs adviceArgs)
{
if (adviceArgs.Instance.GetType() == cuckooType)
return new MyClassSwapperAttribute();

return this.MemberwiseClone();
}

public void RuntimeInitializeInstance()
{
if (this.cuckooType == null)
return;

// for each instance of the target class we create a new cuckoo's egg instance
this.cuckooEgg = Activator.CreateInstance(cuckooType);
}

public override void OnInvoke(MethodInterceptionArgs args)
{
if (this.cuckooEgg == null)
{
base.OnInvoke(args);
}
else
{
// delegate the method invocation to the cuckoo's egg, that derives from the target class
args.ReturnValue = args.Method.Invoke(this.cuckooEgg, args.Arguments.ToArray());
}
}
}

此实现要求 AnotherClass 派生自 MyClass 并且您必须在 MyClass 本身上应用该属性,例如:

[MyClassSwapper(typeof (AnotherClass))]
class MyClass
{
// ...
}

关于c# - 使用 PostSharp 在 C# 中面向方面的设计模式 Cuckoo's Egg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20149344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com