假设我有以下界面:
public interface IMyService
{
void SimpleMethod(int id);
int Hello(string temp);
}
想要生成一个看起来像这样的类(使用反射发射)。
public class MyServiceProxy : IMyService
{
IChannel _channel;
public MyServiceProxy(IChannel channel)
{
_channel = channel;
}
public void SimpleMethod(int id)
{
_channel.Send(GetType(), "SimpleMethod", new object[]{id});
}
public int Hello(string temp)
{
return (int)_channel.Request(temp);
}
}
我该怎么办?我检查了各种动态代理和模拟框架。它们有点复杂,并不容易遵循(我不想要外部依赖)。生成接口的代理应该不难。谁能告诉我怎么样?
答案 0 :(得分:1)
总而言之,我会同意其他人的意见。我使用过Castle的DynamicProxy,我认为这很精彩。你可以用它做一些非常神奇和强大的东西。也就是说,如果你还在考虑自己编写,请继续阅读:
如果您对发射IL不感兴趣,可以使用一些可用于生成代码的Lambda表达式的新技术。然而,这些都不是一项微不足道的任务。
以下是我如何使用Lambda表达式为任何.NET事件生成动态事件处理程序的示例。您可以使用类似的技术来生成动态接口实现。
public delegate void CustomEventHandler(object sender, EventArgs e, string eventName);
Delegate CreateEventHandler(EventInfo evt, CustomEventHandler d)
{
var handlerType = evt.EventHandlerType;
var eventParams = handlerType.GetMethod("Invoke").GetParameters();
//lambda: (object x0, EventArgs x1) => d(x0, x1)
// This defines the incoming parameters of our dynamic method.
// The method signature will look something like this:
// void dynamicMethod(object x0, EventArgs<T> x1)
// Each parameter is dynamically determined via the
// EventInfo that was passed.
var parameters = eventParams.Select((p, i) => Expression.Parameter(p.ParameterType, "x" + i)).ToArray();
// Get the MethodInfo for the method we'll be invoking *within* our
// dynamic method. Since we already know the signature of this method,
// we supply the types directly.
MethodInfo targetMethod = d.GetType().GetMethod(
"Invoke",
new Type[] { typeof(object), typeof(EventArgs), typeof(string) }
);
// Next, we need to convert the incoming parameters to the types
// that are expected in our target method. The second parameter,
// in particular, needs to be downcast to an EventArgs object
// in order for the call to succeed.
var p1 = Expression.Convert(parameters[0], typeof(object));
var p2 = Expression.Convert(parameters[1], typeof(EventArgs));
var p3 = Expression.Constant(evt.Name);
// Generate an expression that represents our method call.
// This generates an expression that looks something like:
// d.Invoke(x0, x1, "eventName");
var body = Expression.Call(
Expression.Constant(d),
targetMethod,
p1,
p2,
p3
);
// Convert the entire expression into our shiny new, dynamic method.
var lambda = Expression.Lambda(body, parameters.ToArray());
// Convert our method into a Delegate, so we can use it for event handlers.
return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
}
此致
-Doug