大家好。我需要Trim
一个String
。但我希望删除字符串本身中所有重复的空格,而不仅仅是在字符串的末尾或开头。我可以使用下面这样的方法:
public static string ConvertWhitespacesToSingleSpaces(string value)
{
value = Regex.Replace(value, @"\s+", " ");
}
这是我从here那里得到的。但我希望这段代码在String.Trim()
本身内调用,所以我认为我需要扩展或重载或覆盖Trim
方法……有没有办法做到这一点?
提前谢谢。
发布于 2011-02-06 06:35:32
因为您不能扩展string.Trim()
。您可以创建一个如here所述的扩展方法来修剪和减少空格。
namespace CustomExtensions
{
//Extension methods must be defined in a static class
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static string TrimAndReduce(this string str)
{
return ConvertWhitespacesToSingleSpaces(str).Trim();
}
public static string ConvertWhitespacesToSingleSpaces(this string value)
{
return Regex.Replace(value, @"\s+", " ");
}
}
}
你可以这样使用它
using CustomExtensions;
string text = " I'm wearing the cheese. It isn't wearing me! ";
text = text.TrimAndReduce();
为您提供
text = "I'm wearing the cheese. It isn't wearing me!";
发布于 2011-02-06 06:31:10
有可能吗?可以,但只能使用扩展方法
类System.String
是密封的,所以您不能使用重写或继承。
public static class MyStringExtensions
{
public static string ConvertWhitespacesToSingleSpaces(this string value)
{
return Regex.Replace(value, @"\s+", " ");
}
}
// usage:
string s = "test !";
s = s.ConvertWhitespacesToSingleSpaces();
发布于 2011-02-06 06:33:13
你的问题有肯定的也有否定的。
可以,您可以使用扩展方法扩展现有类型。自然,扩展方法只能访问该类型的公共接口。
public static string ConvertWhitespacesToSingleSpaces(this string value) {...}
// some time later...
"hello world".ConvertWhitespacesToSingleSpaces()
不能,您不能调用此方法Trim()
。扩展方法不参与重载。我认为编译器甚至应该给你一条详细说明这一点的错误消息。
仅当包含定义方法的类型的命名空间使用‘’ed时,扩展方法才可见。
https://stackoverflow.com/questions/4910108
复制相似问题