在C#中实例化类时使用()或{}

问题描述:

x1和x2的初始化有任何区别吗?在C#中实例化类时使用()或{}

namespace ConsoleApplication2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var x1 = new C { }; 

      var x2 = new C(); 

     } 
    } 

    public class C 
    { 
     public int A; 
    } 
} 
+0

定义相当于“差”。你在寻找性能差异吗?你会使用其中一个的原因?为什么两者都存在的理由? –

+3

出于兴趣,你是否知道这两种语法之间的区别,或者是问题的一部分,不能理解为什么允许这两种不同的调用? – Chris

大括号{}用于对象或集合初始化:

new C() { Property1 = "Value", Property2 = "etc..." }; 

应当指出的是,这里的()可以省略,因为它是默认的构造函数。因此,new C{}基本上是new C() {}

不,他们编译成相同的代码但是

.method private hidebysig static void Main(string[] args) cil managed 
{ 
    .entrypoint 
    // Code size  14 (0xe) 
    .maxstack 1 
    .locals init ([0] class ConsoleApplication2.C x1, 
      [1] class ConsoleApplication2.C x2) 
    IL_0000: nop 
    IL_0001: newobj  instance void ConsoleApplication2.C::.ctor() 
    IL_0006: stloc.0 
    IL_0007: newobj  instance void ConsoleApplication2.C::.ctor() 
    IL_000c: stloc.1 
    IL_000d: ret 
} // end of method Program::Main 

x2是标准的编码风格,配有参数的构造函数处理,而不是使用初始化对象初始化的任何值时。

在你的例子中,没有区别。两者都调用默认构造函数,并且不传入任何值。 {}是对象初始化符号,它允许您在未通过构造函数传入的公共属性上设置值。

Ex。通过以下类,PropertyA通过构造函数传递,PropertyA,PropertyB,PropertyC可以在对象上设置。

class TestClass 
{ 
    public string PropertyA { get; set; } 
    public string PropertyB { get; set; } 
    public string PropertyC { get; set; } 

    public TestClass(string propertyA) 
    { 
     propertyA = propertyA; 
    } 
} 

如果您需要设置所有的值,你可以做到这一点

var test1 = new TestClass("A"); 
test1.PropertyB = "B"; 
test1.PropertyC = "C"; 

或使用对象初始化格式将

var test2 = new TestClass("A") {PropertyB = "B", PropertyC = "C"};