复制代码 代码如下:
namespace Test001
{
public class ParentClass
{
// Constructors
public ParentClass(IEnumerable<string> dataCollection)
{
this.DataCollection = dataCollection;
}
// Properties
public IEnumerable<string> DataCollection { get; private set; }
}
public class ChildClass : ParentClass
{
// Constructors
public ChildClass() : base(new List<string>()) { }
}
}
复制代码 代码如下:
namespace Test002
{
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 = new List<string>();
// Constructors
private ChildClass() : base(_dataCollection) { }
}
}
想了一下,换个角度去解决这个问题。干脆另外再开一个子对象的建构子,先建立要传给父对象的对象,然后不直接传给父对象的建构子,而是传给子对象自己的建构子,然后这个建构子在传递给父对象。写到我眼睛都花了,好像绕口令….。直接看程序代码吧,其实还蛮简单就可以完成这个小小的设计:
复制代码 代码如下:
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;
}
}
}
新闻热点
疑难解答
图片精选