我有一些由静态类组成的逻辑组,例如:
static class A {
static int mutate(int i) { /**implementation*/ };
static double prop(double a, double b) { /**implementation*/ };
}
static class B {
static int mutate(int i) { /**implementation*/ };
static double prop(double a, double b) { /**implementation*/ };
}
在这种情况下,A 和 B 是静态类,它们通过一组函数(例如 mutate)实现相同的行为。我想为此模式使用类似接口(interface)的东西,但是由于静态类无法实现接口(interface),我不确定该怎么做。干净利落地实现此类行为的最佳方式是什么?
编辑:
这是我目前正在做的一个例子。这些类没有状态,所以通常我会将它们设为静态。
Interface IMutator {
int mutate(int i);
}
class A : IMutator {
int mutate(int i) { /**implementation*/ };
}
class B : IMutator {
int mutate(int i) { /**implementation*/ };
}
class C {
public List<IMutator> Mutators;
public C(List<IMutator> mutators) {
Mutators = mutators;
}
}
//Somewhere else...
//The new keyword for A and B is what really bothers me in this case.
var Cinstance = new C(new List<IMutator>() {new A(), new B() /**...*/});
最佳答案
无状态类不必是静态的。 此外,当您想要编写单元测试,或者当您想要提取一些通用接口(interface)(如您的情况)时,静态依赖项不是一个好的选择。
可以使用非静态类,只包含逻辑。例如,人们使用无状态 Controller 构建 ASP .NET 应用程序。
所以,扔掉 static
并提取一个接口(interface)。
关于c# - 将具有相同行为的静态类分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38090624/