C#非常动态调用动态

由网友(听疏雨)分享简介:我想写这在C#:I want to write this in C#: SomeUnknownType x;SuperDuperInvoke(x, "MethodName", param1, param2, param3);SuperDuperInvoke2(x, "MethodName", "param1Strin...

我想写这在C#:

I want to write this in C#:

SomeUnknownType x;

SuperDuperInvoke(x, "MethodName", param1, param2, param3);

SuperDuperInvoke2(x, "MethodName", "param1String", "param2String", "param3String");

获取某个对象我什么都不知道,一个方法的名称,以及参数列表,并调用方法。 SuperDuperInvoke2 假设参数转换的字符串。

Get some object I know nothing about, a method name, and a list of parameters, and just call the method. SuperDuperInvoke2 assumes the parameters are convertible from string.

我相信这样的事情是有可能使用动态的框架......我只是找不到如何...

I assume something like this is possible using the dynamic framework... I just can't find how...

我知道我可以反射做到这一点,但它的丑陋和讨厌...

I know I can do this with Reflection, but it's ugly and annoying...

我会解释自己一点点。

我想用这对一些业务服务器的集成测试。 该服务器有很多不同的组件,可以处理请求,统统装进去的IoC容器。 我要揭露​​一些thees成分,大多是为了测试的,所以我只想接收设备的名称,有什么方法我应该用什么参数调用并调用它。

I want to use this for integration testing of some business server. The server has a lot of different components that can handle requests, all loaded into an IoC container. I need to expose some of thees components, mostly for testing, so I want to just receive the name of the component, what method i should call with what parameters and just call it.

推荐答案

我知道你写的,你不喜欢的反映,这是真的那么丑吗?

I know you wrote that you don't like Reflection but is this really all that ugly?

var result = x.GetType().GetMethod( "MethodName" ).Invoke( x, new object[] { methodParams });

如果该方法可以被重载,你可以叫不上名字只走,还需要知道你要多少个参数与调用它。事情是这样的。

If the method could be overloaded you can't go by name only but also need to know how many parameters you are going to invoke it with. Something like this

var method = x.GetType()
              .GetMethods()
              .First(m => m.Name == "MethodName" && m.GetParameters().Length == 2);
var result = method.Invoke( x, new object[] { methodParams });

这是行不通的,如果你还需要通过类型来匹配您的methodParams。

This will not work if you also need to match your methodParams by type.

阅读全文

相关推荐

最新文章