2013-02-13 34 views
-2
("hello").Remove('e'); 

所以String.Remove有許多重載,其中之一是:String.Remove(int startIndex)NET框架String.Remove(char)方法中的錯誤?

不知怎的,我已經寫了'e'的字符被轉換爲int和錯誤的重載函數被調用。這完全是意料之外的事情。我只需要忍受這一點,還是有可能提交一個bug,以便在(神聖的).NET框架的下一個版本中得到糾正?

+2

這是因爲隱式類型轉換爲int的糟糕設計決定。 – 2013-02-13 13:34:02

+2

@TimSchmelter - 沒有刪除方法,需要一個字符。 – ChrisF 2013-02-13 13:34:39

+3

@ChrisF:不是,但是需要'int'和'char'的隱式轉換爲'int'。這就是爲什麼上面的代碼編譯但是由於超出範圍而拋出runtimew異常的原因。 – 2013-02-13 13:36:08

回答

8

String.Remove具有精確重載,兩者採取int作爲他們的第一個參數。

我相信你正在尋找String.Replace,在

string newString = "hello".Replace("e", string.Empty); 
5

沒有Remove方法,它接受char ...

http://msdn.microsoft.com/en-us/library/143t8z3d.aspx

然而,char可以隱式轉換爲一個int,所以你的情況是。但它不會真的刪除字母e,而是在索引(int)'e'(在您的情況下將在運行時超出範圍)的字符。

如果你想「刪除」信e,則:

var newString = "Hello".Replace("e", ""); 

我預測有可能是一個未來的磨合與字符串的不變性。祝你好運;-)

2

刪除需要一個整數作爲參數,而不是一個字符。 'e'作爲int變成101。

4

請看智能感知的方法:它是:

// 
    // Summary: 
    //  Returns a new string in which all the characters in the current instance, 
    //  beginning at a specified position and continuing through the last position, 
    //  have been deleted. 
    // 
    // Parameters: 
    // startIndex: 
    //  The zero-based position to begin deleting characters. 
    // 
    // Returns: 
    //  A new string that is equivalent to this string except for the removed characters. 
    // 
    // Exceptions: 
    // System.ArgumentOutOfRangeException: 
    //  startIndex is less than zero.-or- startIndex specifies a position that is 
    //  not within this string. 
    public string Remove(int startIndex); 

它做什麼它說;它只是不是你想要的方法。你想要的是:

string s = "hello".Replace("e",""); 
2

你的問題是什麼?

由於沒有以char作爲參數的超載,因此不能期望以這種方式刪除'e'

只需使用string.Replace(string, string)

1

string.Remove()只有2個重載,其中一個接受一個int參數(並且其中沒有一個採用char參數)。

字符可以轉換爲整數。

因此調用string.Remove(int)。

不是一個錯誤。 :)