2014-04-01 31 views
1

雖然我讀的C#擴展方法,我來看看下面這樣編碼:差異「迴歸新」

public static class ExtensionMethods 
{ 
    public static string UpperCaseFirstLetter(this string value) 
    { 
     if (value.Length > 0) 
     { 
      char[] array = value.ToCharArray(); 
      array[0] = char.ToUpper(array[0]); 
      return new string(array); 
     } 
     return value; 
    } 
} 
class Program : B 
{ 
    static void Main(string[] args) 
    { 
     string value = "dot net"; 
     value = value.UpperCaseFirstLetter(); 
     Console.WriteLine(value); 
     Console.ReadLine(); 
    } 
} 

我評論了線,「迴歸新」禮物並運行程序。現在編譯器讀取代碼「返回值」。如果我在沒有評論該行的情況下運行該程序,那麼編譯器不會讀取「返回值」行。 C#中的return和return new有什麼區別?

+3

這些只是兩個'return'語句。當你第一次離開時,程序將一直退出第二次。 'new'是一個普通的對象實例。 –

+0

這與'return'沒有任何關係。他們只是不同的對象 – Jonesopolis

+0

那麼他們在那裏指定了新的關鍵字? – thevan

回答

4

有沒有這樣的事情return new。實際發生的事情是:

string foo = new string(array); 
return foo; 

您正在返回一個字符串的實例。

2

沒有return new,它只是一個return聲明像任何其他。它返回的是new string(array)

如果您對該行註釋,則該方法不會結束,而是退出if塊,然後繼續執行下一個return語句。

1

return關鍵字將跳過執行並返回該函數作爲返回類型的值。在你的例子中它是static string,所以它返回你的字符串。

FROM OP:

I commented the line, "return new" presents and run the program. Now the compiler reads the code "return value". If I run the program without commenting that line, then the compiler not reads the "return value" line. What is the difference between return and return new in C#? 

當你評論線「迴歸新」編譯器執行整個功能塊和「返回值」得到的執行,當「迴歸新」目前有那麼編譯器讀取它並從那裏返回流量。

1

我認爲return讓你感到困惑。把這個邏輯等於代碼:

public static string UpperCaseFirstLetter(this string value) 
{ 
    string result; 

    if (value.Length > 0) 
    { 
     char[] array = value.ToCharArray(); 
     array[0] = char.ToUpper(array[0]); 
     result = new string(array); 
    } 
    else 
    { 
     result = value; 
    } 

    return result; 
} 

new string(array)是調用this constructor,需要一個字符數組,給你的是一個字符串表示。方法簽名指出將返回string。如果您嘗試return array,則會發生編譯器錯誤。

+0

是的。所以我們在這裏使用new關鍵字將char數組轉換爲字符串..正確? – thevan

+1

您正在使用'new'關鍵字實例化一個新字符串,然後調用接受char數組的字符串構造函數重載之一。 – Jonesopolis