【问题标题】:A new expression requires (), [], or {} after type in mvc controller在 mvc 控制器中键入新表达式后需要 ()、[] 或 {}
【发布时间】:2015-03-09 21:59:22
【问题描述】:

这很奇怪,但我在控制器操作方法的以下行中收到此错误 A new expression requires (), [], or {} after type

int[] Numbers = { 1, 2, 3, 4, 5}; or I have also tried
var Numbers = new int[]{1,2,3,4,5}; 

还尝试了一些其他方法来让这条线路正常工作,但它不会。

除了控制器操作方法之外,这完全可以正常工作。对这种奇怪的行为有什么想法吗?

我正在使用 VS 2013 express edition MVC version 5 和 .net framework 4.5

这里是完整的动作方法

 public ActionResult Index()
    {
        var LstMainModel=new List<MainModel>           
        var ids = new int[]{1,2,3,4,5};            
        foreach (var id in ids)
        {
            LstMainModel.Add(new MainModel{Id=id,planeModel=GetPlanes()});
        }

        return View(LstMainModel);
    }

【问题讨论】:

  • 你能检查一下,你的项目中没有名为Numbers的类吗?
  • 这里还有别的东西在起作用。声明是正确的
  • 我已尝试更改变量名称,并且根本没有带数字的类
  • 你能展示包含这个的整个方法吗?
  • 这个answer可以帮到你吗?

标签: c# asp.net-mvc


【解决方案1】:

您的List 错误。

var LstMainModel = new List&lt;MainModel&gt;

应该是

var LstMainModel = new List&lt;MainModel&gt;();

这是一个工作示例:

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

namespace ConsoleApplication1
{
    class Program
    {
        static int Main(string[] args)
        {
            var results = TestMethod();
            foreach (var item in results)
            {
                Console.WriteLine(item.Id);
                Console.WriteLine(item.planeModel);
            }
            Console.ReadKey();
            return 0;
        }

        static List<MainModel> TestMethod()
        {
            var LstMainModel = new List<MainModel>();    
            var ids = new int[] { 1, 2, 3, 4, 5 };
            foreach (var id in ids)
            {
                LstMainModel.Add(new MainModel { Id = id, planeModel = "TestPlane" });
            }

            return LstMainModel;
        }


    }

    class MainModel
    {
        public int Id { get; set; }
        public string planeModel { get; set; }
    }

}

您还可以将foreach 重写为 LINQ 表达式,我认为在这种情况下它变得更具可读性。

static List<MainModel> TestMethod()
{
    var ids = new int[] { 1, 2, 3, 4, 5 };
    return ids.Select(id => new MainModel {Id = id, planeModel = GetPlanes()}).ToList();
}

static String GetPlanes()
{
    return "PlanesTest";
}

【讨论】:

  • 我提到它可以在除控制器中的操作方法之外的所有其他地方使用
【解决方案2】:

它应该按照你的方式工作,但如果不是,

试试这样:(声明数组的大小)

int[] numbers = new int[5] {1, 2, 3, 4, 5};

如果还是不行,那就是别的问题了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2016-09-16
    • 2018-03-11
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 2012-01-12
    相关资源
    最近更新 更多