如何扩展String类

本文关键字:String 扩展 何扩展 | 更新日期: 2023-09-27 18:28:30

用javascript扩展核心类非常容易。我觉得在C#中这并不容易。我想给String类添加一些东西,这样我就可以做一些事情,比如:

string s = "the cat's mat sat";
string sql = s.smartsingleQuote();

从而给了我

the cat''s mat sat

这可行吗,或者我必须为此写一个函数吗?

如何扩展String类

是的,可以使用扩展方法-MSDN

这是一个示例代码。

public static class Extns
{
    public static string smartsingleQuote(this string s)
    {
        return s.Replace("'","''");
    }
}

免责声明:未经测试。

是的,您可以使用扩展方法来实现这一点。它看起来像这样:

public static class NameDoesNotMatter {
   public static string smartSingleQuote(this string s) {
      string result = s.Replace("'","''");
      return result;
   } 
}

神奇的是第一个论点前面的关键词"this"。然后你可以写你的代码,它会起作用:

string s = "the cat's mat sat";
string sql = s.smartsingleQuote();

由于字符串类是sealed ,您无法完全完成您所说的内容

你可以通过创建一个扩展方法来实现这个美学

public static class StringExtensions
{
  public static string SmartSingleQuote(this string str)
  {
    //Do stuff here
  }
}

参数中的this关键字允许您接受该参数并将其放在方法名称前面,以便更容易地进行链接,就像您在问题中要求的那样。然而,这相当于:

StringExtensions.SmartSingleQuote(s);

这取决于你当时的偏好:)

以下是关于扩展方法的一个很好的SO答案