我有一个类存储要调用的 WS 方法的名称以及服务接收的唯一参数的类型和值(它将是参数的集合,但让示例保持简单):
public class MethodCall
{
public string Method { get; set; }
public Type ParType { get; set; }
public string ParValue { get; set; }
public T CastedValue<T>()
{
return (T)Convert.ChangeType(ParValue, ParType);
}
}
我有一个方法,它采用方法名称和参数,并使用反射调用该方法并返回结果。当我像这样使用它时,它可以正常工作:
callingclass.URL = url;
callingclass.Service = serviceName;
object[] Params = { (decimal)1 };
callingclass.CallMethod("Hello", Params);
但是我的类型,示例中的十进制,是在 MethodCall 的实例中给出的。所以如果我有这个代码:
MethodCall call = new MethodCall();
call.Method = "Hello";
call.ParType = typeof(decimal);
call.ParValue = "1";
选项 1,不编译:
object[] Params = { (call.ParType)call.ParValue }; //Compilation error: The type or namespace name 'call' could not be found (are you missing a using directive or an assembly reference?)
选项 2,也不编译:
object[] Params = { call.CastedValue<call.ParType>() }; //Compilation error: Cannot implicitly convert type 'call.ParType' to 'object'
选项 3,使用反射,编译但在调用服务时不起作用:
object[] Params = { typeof(MethodCall).GetMethod("CastedValue").MakeGenericMethod(call.ParType).Invoke(this, null) };
callingclass.CallMethod(call.Method, Params);
例外情况是: ConnectionLib.WsProxyParameterExeption:URL ' http://localhost/MyTestingService/ ' 中方法'TestService.Hello' 的参数错误。
那么有人可以指出我正确的方法来完成这项工作吗?
谢谢