2

在 javascript 中扩展核心类非常容易。我的印象是在 C# 中并不那么容易。我想在 String 类中添加一些东西,以便我可以执行以下操作:

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

因此给了我

the cat''s mat sat

这是否可行,还是我必须为此编写一个函数?

4

3 回答 3

12

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

这是一个示例代码。

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

免责声明:未经测试。

于 2013-08-22T04:25:48.260 回答
3

你不能完全完成你所说的字符串类是sealed

您可以通过创建扩展方法来完成此美学

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

参数中的this关键字允许您获取该参数并将其放在方法名称的前面,以便更轻松地链接,就像您在问题中要求的那样。但是,这相当于:

StringExtensions.SmartSingleQuote(s);

这仅取决于您当时的喜好:)

这是关于扩展方法的一个很好的答案

于 2013-08-22T04:26:25.697 回答
3

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

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();
于 2013-08-22T04:27:04.980 回答