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

发布于 2024-10-15 23:29:30 字数 421 浏览 4 评论 0原文

我需要修剪一个字符串。但我想删除字符串本身内所有重复的空格,而不仅仅是在其末尾或开头。我可以用这样的方法来做到这一点:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

把昨日还给我 2024-10-22 23:29:30

因为您无法扩展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+", " ");
        }
    }
}

你可以像这样使用它

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!";

Since you cannot extend 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!";
儭儭莪哋寶赑 2024-10-22 23:29:30

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

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

Is it possible? Yes, but only with an extension method

The class System.String is sealed so you can't use overriding or inheritance.

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

// usage: 
string s = "test   !";
s = s.ConvertWhitespacesToSingleSpaces();
长途伴 2024-10-22 23:29:30

对于你的问题,有一个是,也有一个不是。

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

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

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

不,您不能调用此方法 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.

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

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

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.

浸婚纱 2024-10-22 23:29:30

扩展方法!

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

Extension methods!

public static class MyExtensions
{
    public static string ConvertWhitespacesToSingleSpaces(this string value)
    {
        return Regex.Replace(value, @"\s+", " ");
    }
}
薄荷梦 2024-10-22 23:29:30

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

快乐编码。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文