侧边栏壁纸
  • 累计撰写 185 篇文章
  • 累计创建 77 个标签
  • 累计收到 17 条评论

目 录CONTENT

文章目录

C#中如何为string类添加扩展的方法

码峰
2022-09-05 / 0 评论 / 0 点赞 / 989 阅读 / 206 字 / 正在检测是否收录...
广告 广告

在C#中,提供了可以给类增加扩展方法的特性,扩展方法后,只需要通过[对象名].[方法名]就可以调用扩展的方法,调用上非常简洁清晰,下面以string类为例,介绍一下扩展方法。示例代码如下:

public static class Utility
{
    public static int GetIntNumber(this string s)
    {
        int ret = 0;
        try
        {
            ret = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(s, @"[^0-9]+", ""));
        }
        catch { }
        return ret;
    }
}

以上代码是给string类扩展了一个GetIntNumber的方法,这个方法通过正则表达式获取字符串中的数字,并将数字内容转换为整数返回。调用示例如下:

string s = "num123";
var num = s.GetIntNumber();
Console.WriteLine("num is {0}", num);

以上代码执行后输出:

num is 123
0
广告 广告

评论区