简体   繁体   English

如何扩展 C# 内置类型,如 String?

[英]How to extend C# built-in types, like String?

Greetings everyone... I need to Trim a String .大家好...我需要Trim一个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.但是我想删除 String 本身中所有重复的空格,而不仅仅是在它的末尾或开头。 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?但是我希望在String.Trim()本身中调用这段代码,所以我认为我需要扩展或重载或覆盖Trim方法......有没有办法做到这一点?

Thanks in advance.提前致谢。

Since you cannot extend string.Trim() .因为你不能扩展string.Trim() You could make an Extension method as described here that trims and reduces whitespace.您可以按照此处所述制作一个扩展方法来修剪和减少空格。

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+", " ");
        }
    }
}

You can use it like so你可以像这样使用它

using CustomExtensions;

string text = "  I'm    wearing the   cheese.  It isn't wearing me!   ";
text = text.TrimAndReduce();

Gives you给你

text = "I'm wearing the cheese. It isn't wearing me!";

Is it possible?有可能吗? Yes, but only with an extension method是的,但只能使用扩展方法

The class System.String is sealed so you can't use overriding or inheritance. 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();

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.扩展方法自然只能访问该类型的公共接口。

public static string ConvertWhitespacesToSingleSpaces(this string value) {...}

// some time later...
"hello world".ConvertWhitespacesToSingleSpaces()

No, you cannot call this method Trim() .不,您不能调用此方法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!扩展方法!

public static class MyExtensions
{
    public static string ConvertWhitespacesToSingleSpaces(this string value)
    {
        return Regex.Replace(value, @"\s+", " ");
    }
}

Besides using extension methods -- likely a good candidate here -- it is also possible to "wrap" an object (eg "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.快乐编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM