Skip to main content
 首页 » 编程设计

c#之在 mvc Controller 中键入后,新表达式需要 ()、[] 或 {}

2024年02月06日14webabcd

这很奇怪,但我收到此错误 A new expression requires (), [], or {} after type on the following line in a controller action method

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

还尝试了其他几种方法来使这条线正常工作,但行不通。

除了 Controller 操作方法之外,这工作得很好。关于这种奇怪的行为有什么想法吗?

我正在使用 VS 2013 Express Edition MVC 版本 5 和 .net framework 4.5

这里是完整的 Action 方法

 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); 
    } 

请您参考如下方法:

你的 List是错误的。

var LstMainModel = new List<MainModel>

应该是

var LstMainModel = new List<MainModel>();

这是一个工作示例:

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"; 
}