簡體   English   中英

這個初始化方法有什么區別?

[英]What is the difference between this initialization methods?

這兩個代碼有什么區別?

class SomeClass   
{   

   SomeType val = new SomeType();   

}   

class SomeClass  
{      
   SomeType val;   

   SomeClass()   
   {   
       val = new SomeType();   
   }   

}   

選擇哪種方法?

他們之間幾乎沒有差別。 在兩種情況下,字段的賦值都將在構造函數中發生。 但是,與基類構造函數相比,它有多么不同。 請使用以下代碼:

class Base
{
    public Base()
    {

    }
}

class One : Base
{
    string test = "text";
}

class Two : Base
{
    string test;
    public Two()
    {
        test = "text";
    }
}

在這種情況下,基類構造函數將在類One的字段賦值之后Two類中的賦值之前調用。

第一個版本允許您定義多個構造函數,而不必記住在每個構造函數中放置= new SomeType()

暫無
暫無

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

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