无法初始化类型'int'错误

时间:2013-08-19 06:39:11

标签: c# visual-studio-2010 console-application

我在C#中有一个简单的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyProject
{
  public static class Class1
  {
    public static int[] Iparray = new int { 12, 9, 4, 99, 120, 1, 3, 10 };
  }
}

但是( Ctrl + Shift + B )显示的错误是

Cannot initialize type 'int' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

我正在使用vs 2010和 和.NET framework 4

谢谢大家

7 个答案:

答案 0 :(得分:5)

你缺少括号。像这样:

int[] a = new int[] { 1, 2, 3 };

答案 1 :(得分:3)

您有三种方法来定义int数组:

 public static int[] Iparray = { 12, 9, 4, 99, 120, 1, 3, 10 };

 public static int[] Iparray = new[] { 12, 9, 4, 99, 120, 1, 3, 10 };
 public static int[] Iparray = new int[] { 12, 9, 4, 99, 120, 1, 3, 10 };

答案 2 :(得分:2)

new int[] { 12, 9, 4, 99, 120, 1, 3, 10 };

答案 3 :(得分:1)

试试这个: -

public static int[] a = new int[] {12, 9, 4, 99, 120, 1, 3, 10 };

而不是

public static int[] Iparray = new int { 12, 9, 4, 99, 120, 1, 3, 10 };

答案 4 :(得分:1)

你错过了方括号;

namespace MyProject
{
  public static class Class1
  {
    public static int[] Iparray = new int[] { 12, 9, 4, 99, 120, 1, 3, 10 };
  }
}

声明int数组的其他方式;

  • int[] Iparray = { 12, 9, 4, 99, 120, 1, 3, 10 };

  • int[] Iparray = new[] { 12, 9, 4, 99, 120, 1, 3, 10 };

答案 5 :(得分:1)

int[] values = new int[] { 1, 2, 3 };
or this:

int[] values = new int[3];
values[0] = 1;
values[1] = 2;
values[2] = 3;

并查看此http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

答案 6 :(得分:1)

将[]添加到您的代码

public static int[] Iparray = new int[] { 12, 9, 4, 99, 120, 1, 3, 10 };