如何延长C#内置类型,如String? [英] How to extend C# built-in types, like String?

查看:183
本文介绍了如何延长C#内置类型,如String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问候大家...我需要修剪 A 字符串。但我想String中删除所有重复空格,不仅在年底或在它的开始。我可以用一个方法做到这一点,如:

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

这是我从来到这里。但我想这件作品code的内被称作 String.Trim()本身,所以我想我需要延长或过载或重写修剪方法...有没有办法做到这一点?

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()。你可以做的描述 href=\"http://msdn.microsoft.com/en-us/library/bb311042.aspx\">扩展方法是修剪和减少的空白。

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

您可以使用它像这样

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

这篇关于如何延长C#内置类型,如String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆