我有一個類,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_是隻讀的,您可以隨時更改**內容**。顯而易見的解決方案,然後.... –