带有 JSON 个参数的 C# MethodInfo Invoke()

C# MethodInfo Invoke() with JSON args

MethodInfo 对象上的 Invoke() 函数接受参数作为 object[]。我希望能够发送 JSON 编码的字符串。有什么办法吗?

我基于我的代码来自 this MSDN page

....
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);

//args in this case is an object[]. any way to pass a string?
return mi.Invoke(wsvcClass, args);

我知道 Newtonsoft 提供了一种反序列化字符串的方法,但它可以反序列化为 object[] 吗?还是有另一种方法可以做到这一点?

您正在查看的方法签名采用 Object[] 表示方法中的所有参数。例如:

public void DoStuff(string x, string y, int b);

可以这样称呼:

methodInfo.Invoke(wscvClass, new object[] { "x", "y string", 500 });

因此,在您的情况下,您应该能够使用以下方式调用 Invoke

string jsonEncodedString = "{ }"; // whatever you need to do to get this value
mi.Invoke(wsvcClass, new object[] { jsonEncodedString });

MethodInfo MSDN Link