将数组从Web服务返回到客户端控制台

时间:2015-03-19 01:00:12

标签: c# arrays web-services

我正在尝试使用我在c#中使用Visual Studio 2010编写的Web服务返回一个Fibonacci数字序列。 这是我创建序列并将其存储在数组'Fibon'中以返回客户端程序的函数。

 public class Service1 : System.Web.Services.WebService
 {
    [WebMethod]
    public long[] Fibonacci(int length) 
    {
        long[] Fibon;
        Fibon = new long [length]; 
        Fibon[0] = 0;
        Fibon[1] = 1;

        for (int i = 2; i < length; i++)
        {
            Fibon[i] = Fibon[i - 2] + Fibon[i - 1];
        }

        return Fibon;
    }
 }`

调用该函数的客户端程序如下:

 class Program
 {
    static void Main(string[] args)
    {
        Service1 webservice = new Service1();   
        Console.Out.Write("\nHow many number of the Fibonacci sequence do you want returned?\n");
        int Number = Convert.ToInt32(Console.In.ReadLine());
        long[] Sequence = new long[Number];
        Sequence = webservice.Fibonacci(Number);    // PROBLEM LINE ********
        Console.Out.Write("\nThe Sequence is \n\n");
        for (int i = 0; i <= Number; i++)
        { 
            Console.WriteLine(Sequence[i]);
        }
        Console.Out.Write(",  \n\nPress ENTER to return");
        Console.ReadLine();
    }
}

我收到错误“无法将类型'int'隐式转换为'long []” 当我运行该功能并在浏览器上对其进行测试时,它正在运行但返回客户端控制台却出错。我做错了什么?

2 个答案:

答案 0 :(得分:0)

我已经按照你的建议Peyman和解决方案工作了。我还必须从我的代码中更改行

    int Number = Convert.ToInt32(Console.In.ReadLine());                                                                                                  
    long[] Sequence = new long[Number];
    Sequence = webservice.Fibonacci(Number);

到代码中的建议行

    var Number = Convert.ToInt32(Console.In.ReadLine());            
    var Sequence = webservice.Fibonacci(Number); 

现在代码运行并根据需要返回序列。非常感谢!!!!!

答案 1 :(得分:-1)

该行不应该有错误,只应该在for循环中有问题:

class Program
 {
    static void Main(string[] args)
    {
        Service1 webservice = new Service1();   
        Console.Out.Write("\nHow many number of the Fibonacci sequence do you want returned?\n");
        var Number = Convert.ToInt32(Console.In.ReadLine());            
        var Sequence = webservice.Fibonacci(Number);    
        Console.Out.Write("\nThe Sequence is \n\n");
        for (int i = 0; i < Number; i++) // Fixed LINE ********
        { 
            Console.WriteLine(Sequence[i]);
        }
        Console.Out.Write(",  \n\nPress ENTER to return");
        Console.ReadLine();
    }
}