见下面的代码:
new ConditionCreator()
.Add()
.Or()
.Add()
.And()
.Add()
我想为此创建一个流畅的界面 但是我需要, 在 Add() 方法开发人员看到 Only Or() 或 And() 之后 和 在其中之一之后,请参阅 Only Add() 方法。
所以没有人可以写这样的代码:
new ConditionCreator()
.Add()
.Add()
.Add()
.Or()
.And()
.Add()
.And()
.And()
我想限制某些方法可以接受特殊方法等。 我可以在一个类中编写所有方法并为每个方法返回它,但这不合适!!!
请指导我如何编写 Advanced Fluent Interface 类。
最佳答案
要限制事物,您需要创建并返回一个(可能是几个)可以执行特殊操作的“构建器”对象,并保留对主类的引用。
public class ConditionCreator
{
public ConditionCreator() { ... }
public SubConditionCreator Add() { ...; return new SubConditionCreator(this); }
internal ConditionCreator OnAdd() { ...; return this; };
internal ConditionCreator OnOr() { ...; return this; };
}
public class SubConditionCreator
{
private ConditionCreator _creator;
internal SubConditionCreator(ConditionCreator c) { _creator = c; }
public ConditionCreator And() { return _creator.OnAdd(); }
public ConditionCreator Or() { return _creator.OnOr(); }
}
使用内部访问限制使用。
为了避免产生垃圾,在主类中存储一个 SubConditionCreator ref
关于c# - 如何在 C# 中创建 Fluent Interface 并对某些方法有一些限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36862004/