문제

Extending core classes in javascript is dead easy. I get the impression it's not quite so easy in C#. I was wanting to add some things to the String class so that I could do stuff like:

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

thus giving me

the cat''s mat sat

Is that even feasible, or do I have to write a function for that?

도움이 되었습니까?

해결책 2

Yes you can do this, with an extension method. It'll look something like that:

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

The magic is the keyword "this" in front of the first argument. Then you can write your code and it'll work:

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

다른 팁

Yes it is possible using Extension Methods - MSDN

Here is a sample code.

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

Disclaimer : Not tested.

You cannot accomplish exactly what you are talking about as the string class is sealed

You can accomplish the aesthetic of this by creating an extension method

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

The this keyword in the parameter allows you to take that parameter and put it in front of the method name for easier chaining like you requested done in your question. This, however, is equivalent to:

StringExtensions.SmartSingleQuote(s);

It just depends on your preference at that point :)

Here is a good SO answer on extension methods

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top