2010-10-11 53 views
5

型后我下面的教程创建一个类:C#编译错误CS1526:一种新的表达需要(),[],或{}

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

有谁知道我在做什么错?

+1

试试这个:Vehicle my_Car = new Vehicle(); – Crag 2010-10-11 19:19:46

回答

13

使用

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}
4

的语法应为:

Vehicle my_Car = new Vehicle(); 
2

尝试new Vehicle()

1

假设您正在使用C#3或更高版本的工作,你也可以使用隐式类型,并做到这一点:

var my_Car = new Vehicle(); 

同样IL是在两种情况下都产生。