如何扩展 C# 内置类型,例如 String?
我需要修剪
一个字符串
。但我想删除字符串本身内所有重复的空格,而不仅仅是在其末尾或开头。我可以用这样的方法来做到这一点:
public static string ConvertWhitespacesToSingleSpaces(string value)
{
value = Regex.Replace(value, @"\s+", " ");
}
这是我从这里获得的。但我希望在 String.Trim()
本身内调用这段代码,所以我认为我需要扩展或重载或重写 Trim
方法...有办法做到这一点吗?
I need to Trim
a String
. But I want to remove all the repeated blank spaces within the String itself, not only at the end or at the start of it. I could do it with a method like:
public static string ConvertWhitespacesToSingleSpaces(string value)
{
value = Regex.Replace(value, @"\s+", " ");
}
Which I got from here. But I want this piece of code to be called within the String.Trim()
itself, so I think I need to extend or overload or override the Trim
method... Is there a way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为您无法扩展
string.Trim()
。您可以按照此处所述创建一个扩展方法来修剪和减少空格。你可以像这样使用它
给你
Since you cannot extend
string.Trim()
. You could make an Extension method as described here that trims and reduces whitespace.You can use it like so
Gives you
是否可以?是的,但只能使用扩展方法
System.String
类是密封的,因此您不能使用重写或继承。Is it possible? Yes, but only with an extension method
The class
System.String
is sealed so you can't use overriding or inheritance.对于你的问题,有一个是,也有一个不是。
是的,您可以使用扩展方法来扩展现有类型。扩展方法自然只能访问该类型的公共接口。
不,您不能调用此方法
Trim()
。扩展方法不参与重载。我认为编译器甚至应该给你一条详细说明这一点的错误消息。仅当包含定义方法的类型的命名空间正在使用时,扩展方法才可见。
There's a yes and a no to your question.
Yes, you can extend existing types by using extension methods. Extension methods, naturally, can only access the public interface of the type.
No, you cannot call this method
Trim()
. Extension methods do not participate in overloading. I think a compiler should even give you a error message detailing this.Extension methods are only visible if the namespace containing the type that defines the method is using'ed.
扩展方法!
Extension methods!
除了使用扩展方法(这里可能是一个很好的候选者)之外,还可以“包装”对象(例如“对象组合”)。只要包装的形式不包含比被包装的东西更多的信息,那么包装的项目就可以通过隐式或显式转换干净地传递,而不会丢失信息:只是类型/接口的更改。
快乐编码。
Besides using extension methods -- likely a good candidate here -- it is also possible to "wrap" an object (e.g. "object composition"). As long as the wrapped form contains no more information than the thing being wrapped then the wrapped item may be cleanly passed through implicit or explicit conversions with no loss of information: just a change of type/interface.
Happy coding.