想了一下,換個角度去解決這個問題。干脆另外再開一個子對象的建構子,先建立要傳給父對象的對象,然後不直接傳給父對象的建構子,而是傳給子對象自己的建構子,然後這個建構子在傳遞給父對象。寫到我眼睛都花了,好像繞口令….。直接看程序代碼吧,其實還蠻簡單就可以完成這個小小的設計:
復制代碼 代碼如下:
namespace Test003
{
public class ParentClass
{
// Constructors
public ParentClass(IEnumerable<string> dataCollection)
{
this.DataCollection = dataCollection;
}
// Properties
public IEnumerable<string> DataCollection { get; private set; }
}
public class ChildClass : ParentClass
{
// Fields
private readonly List<string> _dataCollection = null;
// Constructors
public ChildClass() : this(new List<string>()) { }
private ChildClass(List<string> dataCollection)
: base(dataCollection)
{
_dataCollection = dataCollection;
}
}
}