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

Gir*_*rdi 84 c# string extension-methods trim

大家问候......我需要Trim一个String.但我想删除String本身内的所有重复空格,不仅仅是在结尾或开头.我可以通过以下方法来实现:

public static string ConvertWhitespacesToSingleSpaces(string value)
{
    value = Regex.Replace(value, @"\s+", " ");
}
Run Code Online (Sandbox Code Playgroud)

我从这里得到了什么.但我希望在String.Trim()自身内部调用这段代码,所以我认为我需要扩展或重载或覆盖该Trim方法......有没有办法做到这一点?

提前致谢.

Joe*_*aud 154

因为你不能扩展string.Trim().你可以在这里描述一个扩展方法来修剪和减少空格.

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+", " ");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它

using CustomExtensions;

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

给你

text = "I'm wearing the cheese. It isn't wearing me!";
Run Code Online (Sandbox Code Playgroud)


Hen*_*man 23

可能吗?是的,但只能使用扩展方法

该类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();
Run Code Online (Sandbox Code Playgroud)

  • 要清楚,不,不可能修改`String.Trim`采取的操作. (5认同)

Arn*_*rne 10

对你的问题有一个肯定和否定.

是的,您可以使用扩展方法扩展现有类型.当然,扩展方法只能访问该类型的公共接口.

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

// some time later...
"hello world".ConvertWhitespacesToSingleSpaces()
Run Code Online (Sandbox Code Playgroud)

不,你不能调用这个方法Trim().扩展方法不参与重载.我认为编译器甚至应该给你一个详细说明的错误信息.

仅当包含定义方法的类型的命名空间使用时,扩展方法才可见.


Cor*_*old 7

扩展方法!

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