【发布时间】:2016-12-29 11:35:05
【问题描述】:
我有一个包含多个方法的类,例如:
class mySqlTool{
private string _values, _table, _condition, _result;
public mySqlTool Select(string values = null){
//this is REQUIRED
_values = string.Format("select {0} ", values);
return this;
}
public mySqlTool Update(string table){
//this is REQUIRED
_table = table;
return this;
}
public mySqlTool Set(string name, String value){
//this is REQUIRED
//handle name and value
return this;
}
public mySqlTool From(string table = null){
//this is REQUIRED
_table = table;
return this;
}
public mySqlTool Where(string condition = null){
//this is OPTIONAL
_condition = condition;
return this;
}
public string Execute(){
//this is REQUIRED
//this is samplecode, of course here is checked if its select or update
//but to keep it short i erased it
statement = string.Format("{0} {1}", _values, _table);
if (!string.IsNullOrEmpty(_condition))
{
statement += string.Format(" where {0}", _condition);
}
//do some with statemen and fill result
return _result;
}
}
现在我以这种链接方式使用它:
MySqlTool t = new MySqlTool();
string result = t.Select("a,b,c").From("x").Where("foo=bar").Execute();
当我点击 DOT (.) 时,我的 VS 为我提供了可用的方法。
我的问题是,我想在使用其他方法之前拒绝使用某些方法,例如:
MySqlTool.Where().Select().From().Execute();
在这种情况下,.C() 不应在调用 .A() 之前被调用。所以为了澄清什么是允许的,什么是不允许的,这里有一个小清单
//Allowed
t.Select().From().Execute();
t.Select().From().Where().Execute();
t.Update().Set().Set().Set().Where().Where().Where().Execute();
//not Allowed
t.Select().Where().Execute();
t.Select().Select().Select().From().Execute();
t.From()...
t.Where()...
t.Execute()....
我阅读了一些关于接口和状态的信息,但我不确定这是否是我正在搜索的内容。
所以我的问题:
这是我想要的吗?
如果是,这个技术是怎么命名的?
【问题讨论】:
-
.net 的状态机?
-
这种技术被称为“流利的接口”。
-
不是在编译时,在运行时你可能会携带一个状态。只是...不要。
-
检查这个类似的问题:stackoverflow.com/questions/41319485/…
标签: c# chaining method-chaining