webmethod int到列表和上的字符串

本文关键字:字符串 列表 int webmethod | 更新日期: 2023-09-27 18:26:48

我试图从web服务获取列表的总和。

[WebMethod]
public string CalculateSum(List<int> listInt)
{
       int[] sum = listInt.ToArray();
        return sum; // error under sum on this line
}

但是我得到错误无法将int转换为字符串,这应该工作吗?

客户代码:

    public partial class Form1 : Form
    {
        List<int> listInt = new List<int>();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
        private void button1_Click(object sender, EventArgs e)
        {
            listInt.Add(Convert.ToInt32(textBox1.Text));
            textBox1.Clear();
            listBox1.Items.Clear();
            for (int i = 0; i < listInt.Count; i++)
            {
                listBox1.Items.Add(listInt[i]);
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            CalculateSumOfList.ServiceReference1.Service1SoapClient client = new CalculateSumOfList.ServiceReference1.Service1SoapClient();
            CalculateSumOfList.ServiceReference1.ArrayOfInt arrayOfInt = new CalculateSumOfList.ServiceReference1.ArrayOfInt();
            arrayOfInt.AddRange(listInt);
            int result = client.CalculateSum(arrayOfInt); //here
            label1.Text = Convert.ToString(result);

        }

    }
}

client.CalculateSum(arrayOfInt); 出现错误

webmethod int到列表和上的字符串

[WebMethod]
public int CalculateSum(List<int> listInt)
{
    int sum = listInt.Sum();
    return sum; // error under sum on this line
}

注意函数的返回值——您声明它返回的是字符串而不是整数。

您可以使用任一

 return sum.ToString();

return "" + sum;

但首先要考虑:求int值和的函数真的应该返回字符串吗?作为int函数,它似乎更有意义:

public int CalculateSum(List<int> listInt)
{
    int sum = listInt.Sum();
    return sum;  // now matches the return-type of the method 
}