首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何扩展C#内置类型,比如String?

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

Stack Overflow用户
提问于 2011-02-06 06:28:37
回答 5查看 96.7K关注 0票数 93

大家好。我需要Trim一个String。但我希望删除字符串本身中所有重复的空格,而不仅仅是在字符串的末尾或开头。我可以使用下面这样的方法:

代码语言:javascript
复制
public static string ConvertWhitespacesToSingleSpaces(string value)
{
    value = Regex.Replace(value, @"\s+", " ");
}

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

提前谢谢。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-02-06 06:35:32

因为您不能扩展string.Trim()。您可以创建一个如here所述的扩展方法来修剪和减少空格。

代码语言:javascript
复制
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+", " ");
        }
    }
}

你可以这样使用它

代码语言:javascript
复制
using CustomExtensions;

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

为您提供

代码语言:javascript
复制
text = "I'm wearing the cheese. It isn't wearing me!";
票数 174
EN

Stack Overflow用户

发布于 2011-02-06 06:31:10

有可能吗?可以,但只能使用扩展方法

System.String是密封的,所以您不能使用重写或继承。

代码语言:javascript
复制
public static class MyStringExtensions
{
  public static string ConvertWhitespacesToSingleSpaces(this string value)
  {
    return Regex.Replace(value, @"\s+", " ");
  }
}

// usage: 
string s = "test   !";
s = s.ConvertWhitespacesToSingleSpaces();
票数 24
EN

Stack Overflow用户

发布于 2011-02-06 06:33:13

你的问题有肯定的也有否定的。

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

代码语言:javascript
复制
public static string ConvertWhitespacesToSingleSpaces(this string value) {...}

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

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

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

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4910108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档