【问题标题】:c# compiler error CS1526: A new expression requires (), [], or {} after typec# 编译器错误 CS1526: A new expression requires (), [], or {} after type
【发布时间】:2010-10-11 19:17:03
【问题描述】:

我正在按照教程创建一个类:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Session3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Vehicle my_Car = new Vehicle;
        }
    }
    class Vehicle
    {
        uint mileage;
        byte year;
    }
}

我在这一行收到提到的错误:

private void button1_Click(object sender, EventArgs e)
{
    Vehicle my_Car = new Vehicle;
}

有谁知道我做错了什么?

【问题讨论】:

  • 试试这个:Vehicle my_Car = new Vehicle();

标签: c# constructor compiler-errors


【解决方案1】:

使用

Vehicle my_Car = new Vehicle();

要调用构造函数,你需要在类名后面加上(),就像函数调用一样。

需要满足以下条件之一:

  • () 用于构造函数调用。例如new Vehicle()new Vehicle(...)
  • {} 作为初始化器,例如new Vehicle { year = 2010, mileage = 10000}
  • [] 用于数组,例如new int[3]new int[]{1, 2, 3} 甚至只是 new []{1, 2, 3}

【讨论】:

    【解决方案2】:

    语法应该是:

    Vehicle my_Car = new Vehicle();
    

    【讨论】:

      【解决方案3】:

      试试new Vehicle()

      【讨论】:

        【解决方案4】:

        假设您使用的是 C# 3 或更高版本,您还可以使用隐式类型并执行以下操作:

        var my_Car = new Vehicle();
        

        在这两种情况下都会产生相同的 IL。

        【讨论】:

          【解决方案5】:

          只是进一步澄清并添加参考链接, 使用new Operator 语法分配新内存空间的语法是, 创建对象

           Class1 obj  = new Class1();
          

          创建匿名类型的实例

                var query = from cust in customers  
                   select new { Name = cust.Name, Address = cust.PrimaryAddress };
          

          调用值类型的默认构造函数

          int i = new int();  
          

          简而言之,正如上面的答案已经说明的那样,它是一个缺少括号,这是为对象动态分配内存所必需的。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-01-14
            • 2011-12-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-03-09
            相关资源
            最近更新 更多