将参数数组传递给Web方法

Cic*_*ami 3 c# web-services

我想将一些参数作为数组传递给Web方法.Web方法的签名没有params关键字.

我有一个可变数量的参数(因为web方法接受)所以我不能将数组放入n个单个变量.

如何才能做到这一点?

rsb*_*rro 5

params 只是语法糖,为什么不做这样的事情:

var myWebService = new MyWebService();
myWebService.MyMethod(new string[] { "one", "two", "three" });
Run Code Online (Sandbox Code Playgroud)

Web服务端的方法签名只是:

public void MyMethod(string[] values);
Run Code Online (Sandbox Code Playgroud)

如果您发布您的网络方法,也许我可以提供更好的答案.

编辑
如果您无法修改Web方法签名,那么我将使用扩展方法来包装难以调用的Web服务.例如,如果我们的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以创建一个接受字符串数组的扩展方法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]);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用您创建的扩展方法调用Web服务(只需确保为using您声明扩展方法的命名空间添加一个语句):

var svc = new MyWebService();
svc.MyMethod("this", "is", "a", "test");
Run Code Online (Sandbox Code Playgroud)