我想将一些参数作为数组传递给网络方法。 Web 方法的签名没有 params 关键字。
我有可变数量的参数(正如 web 方法所接受的那样),所以我不能将数组放入 n 个单个变量中。
如何做到这一点?
最佳答案
params
只是语法糖,为什么不做这样的事情:
var myWebService = new MyWebService();
myWebService.MyMethod(new string[] { "one", "two", "three" });
Web 服务端的方法签名只是:
public void MyMethod(string[] values);
如果您发布您的网络方法,也许我可以提供更好的答案。
编辑
如果您无法修改 Web 方法签名,那么我会使用 extension method包装难以调用的网络服务。例如,如果我们的 Web 服务代理类如下所示:
public class MyWebService
{
public bool MyMethod(string a1, string a2, string a3, string a4, string a5,
string a6, string a7, string a8, string a9, string a10)
{
//Do something
return false;
}
}
然后您可以创建一个扩展方法,它接受字符串数组作为 params
并调用 MyWebService
。
public static class MyExtensionMethods
{
public static bool MyMethod(this MyWebService svc, params string[] a)
{
//The code below assumes you can pass in null if the parameter
//is not specified. If you have to pass in string.Empty or something
//similar then initialize all elements in the p array before doing
//the CopyTo
if(a.Length > 10)
throw new ArgumentException("Cannot pass more than 10 parameters.");
var p = new string[10];
a.CopyTo(p, 0);
return svc.MyMethod(p[0], p[1], p[2], p[3], p[4], p[5],
p[6], p[7], p[8], p[9]);
}
}
然后您可以使用您创建的扩展方法调用您的 Web 服务(只需确保为您声明扩展方法的 namespace 添加一个 using
语句):
var svc = new MyWebService();
svc.MyMethod("this", "is", "a", "test");
关于c# - 将参数数组传递给 Web 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5913051/