上下文
我有一个带有call(string method, params object[] arguments)
方法
public class PyroProxy : IDisposable {
public object call(string method, params object[] arguments)
}
这是远程对象的代理类。
动机
在代码中,始终使用call方法看起来不太好。
问题
假设PyroProxy类没有方法test_method()
。
如何使以下代码生效?
PyroProxy p = new PyroProxy();
p.test_method();
test_method
的代码看起来像
public object test_method(params object[] arguments) {
return call("test_method", arguments); // you get the point
}
这可能是我没有找到的重复,也许在编译时或运行时可能。我能做些什么才能更接近这个目标?提示非常感谢。有关如何注入方法的答案。我找到了ExpandoObject,但它没有告诉我如何创建未知方法。
答案 0 :(得分:6)
您应该从DynamicObject
派生,然后覆盖TryInvokeMember
方法。
public class PyroProxy : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
Console.WriteLine(binder.Name + " was invoked");
result = call(binder.Name, args);
return true;
}
}
dynamic proxy = new PyroProxy();
proxy.SomeMethod(); //prints "SomeMethod was invoked"
答案 1 :(得分:3)
为什么不使用extension methods?
public static class ExtensionMethods
{
public static object test_method(this PyroProxy proxy, params object[] arguments)
{
return proxy.call("test_method", arguments); // you get the point
}
}