设计良好的接口方法 [英] Designing Fluent interface methods

查看:137
本文介绍了设计良好的接口方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个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()它返回一个字符串

我希望能够做到

根()和()。AnyInt()这导致一个字符串

推荐答案

该方法应该返回一个包装类。该方法也的的实例方法包装类的的。例如:

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; }
}

您也可以定义从流利隐式或显式转换为字符串,而不是(或除了)的ToString()覆盖。

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

另外,生产code,我会使用一个字符串生成器,以避免多次调用 Concat的

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

这篇关于设计良好的接口方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆