[英]C# Initializing in the constructor not working
我有一個屬性,用於檢查Version Contorl是否為null。 如果為null,則使用tpc.GetService<VersionControlServer>();
設置版本控件的值tpc.GetService<VersionControlServer>();
。 問題是,即使我設置了它,它仍然返回null。
private VersionControlServer versionControl;
public VersionControlServer VersionControl
{
get
{
return this.versionControl;
}
set
{
if (versionControl == null)
{
this.versionControl = this.tpc.GetService<VersionControlServer>();
}
}
}
空支票放在錯誤的位置。 您應該將它放在get
並在那里進行初始化。
每次設置時,您似乎都在重新初始化它。 設置時可能應該使用該value
? 您可以刪除它(是set
),但這會使此屬性為readonly
。
public VersionControlServer VersionControl
{
get
{
if (versionControl == null)
{
this.versionControl = this.tpc.GetService<VersionControlServer>();
}
return this.versionControl;
}
set
{
this.versionControl = value;
}
}
在您設置它的值之前,它將為null
(以便調用您set
訪問器)。
您應該將其更改為此(忽略可能的線程問題):
public VersionControlServer VersionControl
{
get
{
if (versionControl == null)
{
this.versionControl = this.tpc.GetService<VersionControlServer>();
}
return this.versionControl;
}
}
您不需要為此屬性set
一個set
。因為您永遠不會使用value
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.