基于.NET中建構(gòu)子中傳遞子對象的對象詳解
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>()) { }
}
}
但是如果子對象,要使用這個傳遞給父對象的參數(shù),就需要一點小技巧才能取得了。先來看一開始解決的想法是,先建立子對象的屬性對象,然后再傳遞給父對象。這個方法很快就失敗,光是編譯就不過了….。對象的建立是先跑建構(gòu)子、然后生出對象。在建構(gòu)子的階段,就要使用對象的屬性,一定是失敗的。
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) { }
}
}
想了一下,換個角度去解決這個問題。干脆另外再開一個子對象的建構(gòu)子,先建立要傳給父對象的對象,然后不直接傳給父對象的建構(gòu)子,而是傳給子對象自己的建構(gòu)子,然后這個建構(gòu)子在傳遞給父對象。寫到我眼睛都花了,好像繞口令….。直接看程序代碼吧,其實還蠻簡單就可以完成這個小小的設(shè)計:
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;
}
}
}
相關(guān)文章
asp.net實現(xiàn)固定GridView標(biāo)題欄的方法(凍結(jié)列功能)
這篇文章主要介紹了asp.net實現(xiàn)固定GridView標(biāo)題欄的方法,即凍結(jié)列功能,涉及GridView結(jié)合前端js操作數(shù)據(jù)顯示的相關(guān)技巧,需要的朋友可以參考下2016-06-06詳解ASP.NET Core MVC 源碼學(xué)習(xí):Routing 路由
本篇文章主要介紹了詳解ASP.NET Core MVC 源碼學(xué)習(xí):Routing 路由 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03asp.net(c#)下各種進制間的輕松轉(zhuǎn)換(2進制、8進制、10進制、16進制)
在.NET Framework中,System.Convert類中提供了較為全面的各種類型、數(shù)值之間的轉(zhuǎn)換功能。2010-10-10ASP.NET Core環(huán)境設(shè)置教程(2)
這篇文章主要為大家詳細介紹了Asp.net Core環(huán)境設(shè)置教程,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06使用Hangfire+.NET?6實現(xiàn)定時任務(wù)管理(推薦)
這篇文章主要介紹了使用Hangfire+.NET?6實現(xiàn)定時任務(wù)管理,通過引入Hangfire相關(guān)的Nuget包并對Hangfire進行服務(wù)配置,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10