publicclassMyClass : BaseClass { privateMyClass(string someString) : base(someString) { //your code goes in here }
publicstatic MyClass FactoryMethod(string someString) { //whatever you want to do with your string before passing it in returnnew MyClass(someString); } }
重载构造函数调用
在构造函数重载时,可以使用 this 关键字调用同一个类的其他构造函数。示例代码如下:
1 2 3 4 5
publicClassName() : this(par1,par2) { // do not call the constructor it is called in the this. // the base key- word is used to call a inherited constructor }
条件检查调用基类构造函数
可以在构造函数中进行条件检查,然后根据条件调用基类构造函数。示例代码如下:
1 2 3 4 5 6 7 8
publicMyClass(object myObject=null): base(myObject ?? new myOtherObject()) { }
privatestaticintPrepareBaseParameters(int m, outint b, outint c, outobject fatData) { var fd = new { A = 1 * m, B = 2 * m, C = 3 * m }; (b, c, fatData) = (fd.B, fd.C, fd); // Tuples not required but nice to use return fd.A; } }
privatestatic FatData PrepareBaseParameters(int m) { // might be any (non-async) code which e.x. calls factory methods var fd = new FatData(A: 1 * m, B: 2 * m, C: 3 * m); return fd; }
privatereadonlyrecordstructFatData(int A, int B, int C); }