2013-02-13 37 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)。

不是一个错误。 :)