加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:29:28 所属栏目:百科 来源:网络整理
导读:我有一组由静态类组成的逻辑,例如: 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
我有一组由静态类组成的逻辑,例如:
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应用程序.

所以,抛弃静态并提取一个接口.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读