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

标签 c#

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

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/

相关文章:

c# - TripleDESCryptoServiceProvider.Blocksize 不同于 PHP 的 mcrypt_get_key_size

c# - 如何在 Web API Post 方法中返回自定义消息

c# - 这个检查逻辑应该去哪里?

c# - 为什么 ShowGridLines 这么慢?

c# - 在 ASP.NET 中访问 app.config

c# - 桌面开发还是网络开发?

c# - 在 HoloLens 1 上,在使用默认构造函数 "ArgumentException: Value does not fall within the expected range"创建 TcpClient 对象时抛出

c# - 如何使用 Reactive Extensions 解析来自串口的字符流?

c# - 使用 SimpleMembership (MySQL) 将用户添加到角色时出现外键问题

c# - 在 C# 中有条件地实例化一个类