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

时间:2011-02-05 22:28:37

标签: c# string extension-methods trim

向所有人致意......我需要Trim一个String。但我想删除字符串本身内的所有重复空格,不仅仅是在结尾或开头。我可以通过以下方法来实现:

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

我从here得到的。但是我希望在String.Trim()本身内调用这段代码,所以我认为我需要扩展或重载或覆盖Trim方法......有没有办法做到这一点?

提前致谢。

5 个答案:

答案 0 :(得分:144)

因为你无法扩展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!";

答案 1 :(得分:21)

有可能吗?是的,但仅限于扩展方法

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();

答案 2 :(得分:10)

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

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

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

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

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

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

答案 3 :(得分:7)

Extension methods!

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

答案 4 :(得分:2)

除了使用扩展方法 - 这里可能是一个好的候选者 - 还可以“包装”一个对象(例如“对象组合”)。只要包装的表单不包含比被​​包装的东西更多的信息,那么包装的项目可以干净地通过隐式或显式转换而不会丢失信息:只需更改类型/接口。

快乐的编码。

相关问题