我使用C#,这是我的方法。考虑:
class Foo
{
// private fields only to be written inside a constructor
private readonly int i;
private readonly string s;
private readonly Bar b;
// public getter properties
public int I { get { return i; } }
// etc.
}
选项1.带有可选参数的构造函数
public Foo(int i = 0, string s = "bla", Bar b = null)
{
this.i = i;
this.s = s;
this.b = b;
}
用作例如new Foo(5, b: new Bar(whatever))
。不适用于4.0之前的Java或C#版本。但仍然值得展示,因为这是一个示例,说明并非所有解决方案都与语言无关。
选项2.构造函数采用单个参数对象
public Foo(FooParameters parameters)
{
this.i = parameters.I;
// etc.
}
class FooParameters
{
// public properties with automatically generated private backing fields
public int I { get; set; }
public string S { get; set; }
public Bar B { get; set; }
// All properties are public, so we don't need a full constructor.
// For convenience, you could include some commonly used initialization
// patterns as additional constructors.
public FooParameters() { }
}
用法示例:
FooParameters fp = new FooParameters();
fp.I = 5;
fp.S = "bla";
fp.B = new Bar();
Foo f = new Foo(fp);`
从3.0开始的C#使用对象初始化程序语法(在语义上等同于前面的示例)使此操作更加优雅:
FooParameters fp = new FooParameters { I = 5, S = "bla", B = new Bar() };
Foo f = new Foo(fp);
选项3:
重新设计您的类,不需要大量的参数。您可以将其职责划分为多个类别。或根据需要将参数不传递给构造函数,而仅传递给特定方法。并非总是可行的,但是当可行时,这是值得做的。