我可以不用太多使用new来构造组合类吗?

特雷弗·希基(Trevor Hickey)

我有一个基本的类型组成:

class A{
    public A(B1 b1, B2 b2){
        this.b1 = b1;
        this.b2 = b2;
    }
    public B1 b1 {get; private set;}
    public B2 b2 {get; private set;}
}

class B1{
    public B1(C1 c1, C2 c2, C3 c3){
        this.c1 = c1;
        this.c2 = c2;
        this.c3 = c3;
    }
    public C1 c1 {get; private set;}
    public C2 c2 {get; private set;}
    public C3 c3 {get; private set;}
}
class B2{
    public B2(C1 c1, C2 c2, C3 c3){
        this.c1 = c1;
        this.c2 = c2;
        this.c3 = c3;
    }
    public C1 c1 {get; private set;}
    public C2 c2 {get; private set;}
    public C3 c3 {get; private set;}
}

class C1{}
class C2{}
class C3{}

有没有更清洁的构造方法A

public static void Main()
{
    A a = new A(new B1(new C1(), new C2(), new C3()), new B2(new C1(), new C2(), new C3()));
}

我可以不花new太多时间就能达到相同的构造吗?
我可以对我的构造函数做些什么使它成为可能?

斯科特·张伯伦

如果在默认构造函数中A创建了new B,并且在默认构造函数中B创建了C,则可以将其简化为A a = new A();

class A{
    public A() : this(new B1(), new B2())
    {
    }

    public A(B1 b1, B2 b2){
        this.b1 = b1;
        this.b2 = b2;
    }
    public B1 b1 {get; private set;}
    public B2 b2 {get; private set;}
}

class B1{
    public B1() : this(new C1(), new C2(), new C3())
    {
    }

    public B1(C1 c1, C2 c2, C3 c3){
        this.c1 = c1;
        this.c2 = c2;
        this.c3 = c3;
    }
    public C1 c1 {get; private set;}
    public C2 c2 {get; private set;}
    public C3 c3 {get; private set;}
}
class B2{
    public B2() : this(new C1(), new C2(), new C3())
    {
    }

    public B2(C1 c1, C2 c2, C3 c3){
        this.c1 = c1;
        this.c2 = c2;
        this.c3 = c3;
    }
    public C1 c1 {get; private set;}
    public C2 c2 {get; private set;}
    public C3 c3 {get; private set;}
}

class C1{}
class C2{}
class C3{}

public static void Main()
{
    A a = new A();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

我可以使用 willSet 来构造类实例字典条目吗?

可以在类的构造函数内部使用“ new”来调用Java中的另一个构造函数吗?

我可以在初始化派生类时构造基类来分配吗?

我可以使用 for 循环来创建类吗?

我可以使用类来更改 CSS 变量吗?

我可以在nextjs中使用multer而不用express吗?

可以使用C ++聚合初始化来构造实现接口的类的实例吗?

我们可以使用和运算符来组合多个jQuery事件吗

我可以使用类对象实例化一个类吗?构造函数呢?

我可以只用php而不用balanced.js来获得令牌吗?

我可以使用泛型来调用其构造函数吗?

我可以使用类的类型注释来决定类的方法的结果类型吗?

我可以在PHP中使用多个类来扩展一个类吗?

我可以使用类助手来调用静态私有类方法吗?

我可以使用类实例的类来提高可读性吗?

我可以缩小而不用webpack丑化吗

我可以不用这个光标吗

我可以在构造函数中使用 for 吗?

我可以使用接口类强制定义特定的构造函数吗?

我可以使用类型作为值(或从构造函数参数正确推断通用类类型)吗?

我可以在构造方法之外声明Python类字段吗?

我可以使用方法而不是类 Quartz 来定义作业实例吗?

我们可以使用Java关键字来命名类吗?

我可以使用类或列表来提高代码效率吗?

我可以使用C ++中的模板类来做到这一点吗?

我可以使用moq Mock <MyClass>来模拟类,而不是接口吗?

我可以使用invoke来抽象类方法吗

我应该使用new来在打字稿类中创建对象属性吗?

我可以在Scala中使用“收益”来做到这一点吗?(嵌套循环产生组合向量)