简体   繁体   中英

Classify own extension methods

I would like to know if it is possible to "classify" my extension methods.

I created extensions that are coming from SQL world (LEFT / RIGHT / COALESCE / (NOT) IN / (NOT) BETWEEN / ...) and would like to extend it in submethod "SQL" and use it like this :

"abc".SQL().Left(2);

or should I create a static class that reference this methods?

Thanks for any advice and tell me the best practice in this case.

You could create the SQL() as an entension method that returns a class that contains your extensions (as normal methods) that return this new class. The class would have to have a property/field that was your orignal object that called the SQL() method.

EDIT: Thanks to @Kristoffer i now know this is called a fluent interface ; where the API is designed to allow for more readable code.

That is what people call a fluent interface . It's really only the SQL() method that needs to be an extension method (on the string class). The SQL method can then return a class that has the methods like Left() and Coalesce(). If you want to make that extendable, you can extend the class/interface that you SQL method returns.

The methods (Left, Coalesce, etc) can all return the same class/interface, to get the flow of a fluent interface, such as

string b = "abc".SQL().Left(2).Right(1).ToString();

Here's how you can achieve this. The code needs some tweaking, but just to get you started:

First, create a 'builder'-type class that manipulates a string using your Sql methods

 class SqlMethods
 {
      string _target; // probably want to use a StringBuilder instead

      public SqlMethods(string target)
      {
          _target = target;
      }

      SqlMethods Left(int n)
      {
          _target = ...; // implementation of Left()
          return this;
      } 

      public override string ToString() {return _target;}
 }

Instantiate this class through an extension method, like this:

static class StringExtensions
{
     public static SqlMethods SQL(this string s) {return new SqlMethods(s);}
}

This allows for an API like this:

"abc".SQL().Left(2).ToString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM