簡體   English   中英

在C#中實例化類時使用()或{}

[英]Using () or {} when instantiating class in C#

x1和x2的初始化有什么區別嗎?

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

            var x2 = new C ();

        }
    }

    public class C
    {
        public int A; 
    }
}

在您的示例中,沒有區別。 兩者都在調用默認構造函數,並且未傳入任何值。 {}是對象初始值設定項表示法,它允許您在未通過構造函數傳遞的公共屬性上設置值。

例如 對於以下類,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"};

不,它們編譯為相同的代碼

.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是處理無參數構造函數且未使用對象初始化程序初始化任何值時的標准編碼樣式。

大括號{}用於對象或集合的初始化:

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

應該注意的是,這里的()可以省略,因為它是默認的構造函數。 因此, new C{}基本上是new C() {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM