C#非常动态调用 [英] C# very dynamic invocation

查看:150
本文介绍了C#非常动态调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写这在C#:<​​/ P>

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.

这篇关于C#非常动态调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆