2013-11-25 114 views
0

,如果我有字符串:string a = "Hello there"如何擴展方法添加到字符串在C#中

我希望我能做到:a.ReplaceThereSubstring()

,並期待a = "Hello here"

我想是這樣的:

public static class ChangeString 
    { 
     public static string ReplaceThereSubstring(this String myString) 
     { 
      return myString.Replace("there","here"); 
     } 
    } 

但它總是返回null。

你應該這樣做來運行你的代碼的情況下
+7

不,代碼將不會返回null。請展示一個簡短但完整的程序來展示問題。 –

+0

我編輯它。但是我剛剛看到String類是不可變的。我不知道我能否做到這一點。 – mathinvalidnik

+1

你必須重新分配它。 'var a = a.ReplaceThereSubstring();' –

回答

2

string a = "Hello there" 
a = a.ReplaceThereSubstring(); 

不能在擴展方法替換字符串的值,因爲字符串是不變

1

您需要分配結果,課程:

string b = a.ReplaceThereSubString(); 
2

不能修改現有的字符串,因爲strings are immutable

因此像myString.Replace("there", "here");這樣的表達式不會改變myString實例。

您的擴展方法實際上是正確的,但你應該以這種方式使用它:

a = a.ReplaceThereSubstring();