我想在 C# 中实现typestate 模式。我尝试过类似以下方法:
interface Open {}
interface Closed {}
abstract class Foo<T> { }
class Bar<T> where T: Closed { }
class Bar<T> where T: Open { }
以及其他排列,但它们最终都会导致编译器抱怨。这个特定示例给出(来自https://www.programiz.com/csharp-programming/online-compiler/):
/tmp/qmk1tTLHWG.cs(12,11): error CS0101: The namespace 'baz' already contains a definition for 'Bar'
/tmp/qmk1tTLHWG.cs(11,11): error CS0265: Partial declarations of 'Bar<T>' have inconsistent constraints for type parameter 'T'
我对 C# 的类型系统了解不够,不知道什么会真正起作用,而且我找不到太多关于如何做到这一点的文档。是否有可能实现类型状态模式?我找到了Adam 的博客,但他实际上并没有实现图1所示的类型状态模式,如果可能的话,这正是我想要做的。
理想情况下,我想要类似的东西
struct Closed { };
struct Open { };
class Foo<T> {
// functions applicable to Foo's in both the Closed and Open states
}
class Foo<Closed> {
// functions applicable to Foo's in just the Open state
}
class Foo<Open> {
// functions applicable to Foo's in just the Open state
}
您应该通过接口对此进行建模,但只需要一个类。
一个例子:
Foo
您可以通过使用工厂方法强制默认状态来扩展此功能: