Designing Fluent interface methods

≡放荡痞女 提交于 2020-01-03 02:59:48

问题


I am trying to write a DSL

I have methods that return strings but if I want to combine the strings I need to use a + symbol but I would like to call the methods together but I'm unsure how to achieve it

I have methods at the moment such as

MyStaticClass.Root() MyStaticClass.And() MyStaticClass.AnyInt() which return strings

I would like to be able to do

Root().And().AnyInt() which result in a string


回答1:


The methods should return a wrapper class. The methods are also instance methods of the wrapper class. Example:

class Fluent
{
     private string _value;
     public Fluent And()
     {
         this._value += "whatever";
         return this;
     }
     public Fluent AnyInt()
     {
         this._value += "42";
         return this;
     }
     public override string ToString() { return _value; }
}

You could also define an implicit or explicit conversion from Fluent to string, rather than (or in addition to) the ToString() override.

Also, for production code, I'd use a string builder to avoid many calls to Concat.




回答2:


You don't need to use + symbol. Use StringBuilder http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

EXAMPLE

StringBuilder builder = new StringBuilder();
builder.Append("One string ").Append("Second string").Append("Another string");
string final = builder.ToString();  

If you want a simple custom FluentInterface use the following:

public class MyOwnStringBuilder
{
   public StringBuilder Builder;


   public MyOwnStringBuilder()
   {
      this.Builder = new StringBuilder();
   }

   public static MyOwnStringBuilder Root
   {
     get{return new MyOwnStringBuilder();}
   }

   public string End
   {
     get{return Builder.ToString();}
   }

   public MyOwnStringBuilder And(string value)
   {
     Builder.Append(value);
     return this;
   }

   public MyOwnStringBuilder AnyInt(string value)
   {
      Builder.Append(value);
      return this;
   }
}

You would use it:

MyOwnStringBuilder.Root
       .And("some value")
       .AnyInt("some new value")
       .End;

Regards.



来源:https://stackoverflow.com/questions/10157982/designing-fluent-interface-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!