我有一个类,FooBarSet
与一个“核心”块的初始化逻辑。如何与只读类成员共享构造函数代码?
A FooBar
由Foo
和Bar
组成。类别FooBarSet
初始化为FooBar
的列表。 FooBarSet
可以也可以被分开的并行Foo
和Bar
列表初始化。
理想情况下,我可以像这样运行:
public class FooBarSet
{
private readonly List<FooBar> _list;
// Primary constructor.
public FooBarSet(List<FooBar> foobarList)
{
// Contracts and initialization...
_list = foobarList;
}
// Secondary constructor.
public FooBarSet(List<Foo> fooList, List<Bar> barList)
{
// Zip a new list of new FooBars
var zipped = fooList.Zip(barList,
(foo, bar) => new FooBar(foo, bar));
// Call primary constructor with zipped list.
this(zipped);
}
}
这是C#,而不是Java,所以this(zipped)
是非法的。常见的解决办法,as in this answer,就是拉核心初始化成一个共同的私有方法:
public class FooBarSet
{
private readonly List<FooBar> _list;
// Common "constructor" called from actual constructors.
private Init(List<FooBar> foobarList)
{
// Contracts and initialization...
_list = foobarList;
}
public FooBarSet(List<FooBar> foobarList)
{
Init(foobarList);
}
public FooBarSet(List<Foo> fooList, List<Bar> barList)
{
var zipped = fooList.Zip(barList,
(foo, bar) => new FooBar(foo, bar));
Init(zipped);
}
}
然而,这也不行,因为readonly _list
领域。
假设_list
必须是readonly
,我怎样才能让这些构造函数共享初始化代码?
'_list = Init(foobarList)'在构造函数中?使'Init'返回'List'而不是。 –
@RonBeyer,我非常喜欢。它适用于我的实际实施,而不仅仅是我使用的[MWE](https://en.wikipedia.org/wiki/Minimal_Working_Example)。抛弃它作为答案,只要某些疯狂的美丽不会弹出,它就是你的。 – kdbanman
注意:只有列表的_reference_是只读的,您可以随时更改**内容**。显而易见的解决方案,然后.... –