C# 基本构造函数确定
C# base constructor determination
我可以根据 C# 中的一些非实例相关条件来选择基构造函数吗?如果我不能,有什么想法可以满足我的要求吗?谢谢!
class X {}
class Y {}
class A {
public A(X x) {}
public A(Y y) {}
// I don't want to add another constructor with an optional argument
}
class B : A {
private static y = new Y();
// I want to call different base constructor based on the value of argument `x`
public B(X x=null) : base(x!=null? (X)x: (Y)y) {} // x, y here doesn't related to any instance
}
听起来你在找 Factory method:
https://refactoring.guru/design-patterns/factory-method/csharp/example
Factory method is a creational design pattern which solves the problem
of creating product objects without specifying their concrete classes.
Factory Method defines a method, which should be used for creating
objects instead of direct constructor call (new operator). Subclasses
can override this method to change the class of objects that will be
created.
这是一个很好的 C# 示例:
我可以根据 C# 中的一些非实例相关条件来选择基构造函数吗?如果我不能,有什么想法可以满足我的要求吗?谢谢!
class X {}
class Y {}
class A {
public A(X x) {}
public A(Y y) {}
// I don't want to add another constructor with an optional argument
}
class B : A {
private static y = new Y();
// I want to call different base constructor based on the value of argument `x`
public B(X x=null) : base(x!=null? (X)x: (Y)y) {} // x, y here doesn't related to any instance
}
听起来你在找 Factory method:
https://refactoring.guru/design-patterns/factory-method/csharp/example
Factory method is a creational design pattern which solves the problem of creating product objects without specifying their concrete classes.
Factory Method defines a method, which should be used for creating objects instead of direct constructor call (new operator). Subclasses can override this method to change the class of objects that will be created.
这是一个很好的 C# 示例: