背景
using System;
using System.Diagnostics;
namespace Constructor
{
class Program
{
static void Main(string[] args)
{
// [默认值(完全|部分)]
// 简化了参数实例化的代码。
// - 完整表示:var a = new A(2, new B(DateTime.Now));
// 参数越多,嵌套层级越深,简化量越大。
var a = new A(2);
// [默认值+继承]
// - 完整表示:var c = new C1(new B(DateTime.Now));
var c = new C1();
// [非默认值]
var f = new F(1);
var e = new E(f);
var d = new D(e);
}
}
#region 默认参数+无继承
public class A
{
private readonly int x;
private readonly B b;
// [构造器传参]
// 生产时采用默认值。
// 单测时采用特殊值(票根)。
// 因程序员完全掌握代码,不会出现混用默认值的情况。
public A(int x, B b = null)
{
Debug.Assert(x > 0); // 检查|明示值范围
this.x = x;
this.b = b ?? new B();
}
}
public class B
{
private readonly DateTime now;
public B(DateTime now = default(DateTime))
{
this.now = now == default(DateTime)
? DateTime.Now
: now;
}
}
#endregion 默认参数+无继承
#region 默认参数+有继承
public abstract class C
{
protected readonly B b;
public C(B b) => this.b = b ?? new B();
}
public class C1 : C
{
public C1(B b = null) : base(b) { }
}
#endregion 默认参数+有继承
#region 非默认参数
public class D
{
private readonly ISample sample;
// [参数嵌套(x)]
// 单测时模拟接口,生成(x)的单测将难以理解,此时接口是最优解。
// 生产时,必须生成具体(x)。
public D(ISample s) => sample = s;
}
public interface ISample
{
void DoSomething();
}
public class E : ISample
{
private readonly F f;
public E(F f) => this.f = f;
public void DoSomething() { }
}
public class F
{
private readonly int x;
public F(int x) => this.x = x;
}
#endregion 非默认参数
}
网友评论