什么是C#实现代理或者装饰类最短的路?
-
21-08-2019 - |
题
当你有一个汽车类实现IVehicle,你想将其包装在所有呼叫转发到汽车,就会将他们一个装饰,你会怎么做呢?
在Ruby中我可以只建立一个装饰,没有任何方法和使用method_missing的所有呼叫转移到汽车对象。
在爪哇我可以建立通过一个方法运行的所有代码和事后将其转发代理对象。
有什么similiar件事我可以在C#中吗?
更新
基于所述answeres和什么从来就了解System.Reflection.Emit应该是可能写一个方法类同这样:
Type proxyBuilder(Type someType, delagate functionToBeApplied, Object forward)
其中类型实现SOMETYPE的所有接口,执行functionToBeApplied然后转发该方法调用而返回其返回到对象。
有一些lib中,不只是那还是我将不得不写我自己?
解决方案
用于代理你可以看看“RealProxy”如果你想使用标准类型,这是一个麻烦的一点点,虽然使用(它需要你的类从MarshalByRefObject继承而来)。
public class TestProxy<T> : RealProxy where T : class
{
public T Instance { get { return (T)GetTransparentProxy(); } }
private readonly MarshalByRefObject refObject;
private readonly string uri;
public TestProxy() : base(typeof(T))
{
refObject = (MarshalByRefObject)Activator.CreateInstance(typeof(T));
var objRef = RemotingServices.Marshal(refObject);
uri = objRef.URI;
}
// You can find more info on what can be done in here off MSDN.
public override IMessage Invoke(IMessage message)
{
Console.WriteLine("Invoke!");
message.Properties["__Uri"] = uri;
return ChannelServices.SyncDispatchMessage(message);
}
}
另外,您可以从城堡得到“DynamicProxy”。它工作在我的经验好一点..
如果你使用其中的一个,你会不会neccessarily获得出色的,虽然,我用它们主要是在调用,将有可能在第一时间慢..但是你可以尝试一下,如果你想要的。
Marc的溶液将具有更好的性能。
其他提示
不幸的是,在C#没有混入支持。所以,你需要实现所有的方法,或者使用一些重型Reflection.Emit的做到这一点。另一种方法是(可选的)代理/装饰基类...
abstract class FooBase : IFoo {
protected FooBase(IFoo next) {this.next = next;}
private readonly IFoo next;
public virtual void Bar() { // one of the interface methods
next.Bar();
}
public virtual int Blop() { // one of the interface methods
return next.Blop();
}
// etc
}
然后
class SomeFoo : FooBase {
public SomeFoo(IFoo next) : base(next) {}
public override void Bar() {...}
}
注意到使用FooBase
的是可选的;任何的IFoo是允许的。
不隶属于 StackOverflow