将具有相同行为的静态类分组

本文关键字:静态类 | 更新日期: 2023-09-27 17:53:18

我有一组由静态类组成的逻辑,如:

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 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() /**...*/});

将具有相同行为的静态类分组

无状态类不一定是静态的。此外,当您想要编写单元测试时,或者当您想要提取一些公共接口时(就像您的情况一样),静态依赖并不是一个好的选择。

只包含逻辑的非静态类是可以的。例如,人们使用无状态控制器构建asp.net应用程序。

所以,扔掉static,提取一个接口。

除了@Dennis答案(,我有+1'ed,这确实是去的方式),其他方法可能工作,是有一组功能(Func<>)和/或行动(Action<>),并解决他们使用反射。代码不会特别优雅,性能也不会特别好,但它可以工作。

我在dotnetfiddle上做了一个简单的例子