在C#中将列表转换为int数组

时间:2013-10-27 12:35:23

标签: c# list visual-studio-2012 int

我搜索了StackOverflow和Google进行转换,但遗憾的是我无法获得解决方案。一切都与我想要的相反。即,将int[]转换为List

问题

我在[WebMethod]

中有这段代码
[WebMethod]
public int MyMethodWS(int N, List<int> M)
{
}

现在我有一个控制台应用程序,它使用以下网址引用此服务:

http://localhost:61090/MyMethod.asmx?WSDL

我在控制台应用程序中有这个代码:

int N;
List<int> M = new List<int>();
// Some crazy user input coding.
// Ultimately you will have non-empty M list and N int.
MyMethod.MyMethodWS DA = new MyMethod.MyMethodWS();
Sum = DA.MyMethodWS(N, M);

当我运行此代码时,我收到此错误:

  

#1:MyMethod.MyMethod.MyMethodWS(int, int[])”的最佳重载方法匹配包含一些无效参数。

     

#2:参数2:无法从“System.Collections.Generic.List<int>”转换为“int[]

问题

  1. 我在那里只使用了List。但为什么要尝试转换为int[]
  2. 目前,WebService和控制台应用程序都在同一个解决方案中运行。这是个问题吗?我应该使用不同的解决方案,还是Visual Studio 2012的不同实例?

1 个答案:

答案 0 :(得分:2)

它正在尝试将其转换为int[],因为MyMethodWSint[]作为参数,而不是您尝试传递它的List<int>。要将List<int>转换为int[],请致电List<T>.ToArray();

所以将行Sum = DA.MyMethodWS(N, M);更改为Sum = DA.MyMethodWS(N, M.ToArray());