你的代碼等同於以下代碼:
public struct DealImportRequest
{
private DealRequestBase _dr;
private int _irc;
public DealRequestBase DealReq
{
get { return _dr; }
set { _dr = value; }
}
public int ImportRetryCounter
{
get { return _irc; }
set { _irc = value; }
}
/* Note we aren't allowed to do this explicitly - this is didactic code only and isn't allowed for real*/
public DealImportRequest()
{
this._dr = default(DealRequestBase); // i.e. null or default depending on whether this is reference or value type.
this._irc = default(int); // i.e. 0
}
public DealImportRequest(DealRequestBase drb)
{
this.DealReq = drb;
this.ImportRetryCounter = 0;
}
}
現在,所有我在這裏所做的是刪除語法糖是:
- 實現自動屬性。
- 計算出哪些成員處理相對於
this
。
- 提供所有
struct
s默認無參數構造函數。
前兩個是可選的(你可以明確他們寫,如果你願意),但第三個是不是 - 我們不允許我們自己寫的代碼爲struct
的參數的構造函數,我們一起去一個像上面代碼中那樣工作的工具會自動提供給我們。
現在,看看這裏,突然兩個錯誤的含義變得清晰了 - 您的構造函數在分配字段(錯誤188)之前隱式使用this
,而那些字段是支持自動屬性(錯誤843)的字段。
這是不同自動功能的組合,通常我們不必考慮,但在這種情況下效果不佳。我們可以通過下面的在843錯誤信息的建議,並調用默認的構造函數的顯式構造的一部分,解決這個問題:
public DealImportRequest(DealRequestBase drb)
:this()
{
DealReq = drb;
ImportRetryCounter = 0;
}
關於我的擴展上面代碼的版本考慮到這一點,你可以看到這解決了這個問題,因爲它會在繼續進行之前調用分配給後臺字段的構造函數。
可能的重複http://stackoverflow.com/questions/2534960/c-struct-constructor-fields-must-be-fully-assigned-before-control-is-returned – Hps 2010-12-02 14:02:59
@HPS,我不同意。雖然它涉及到與該問題相同的問題,但它與隱式字段相比(支持自動屬性)而不是明確字段的事實足以阻止某人看到這兩個問題相關的原因。這應該足以認爲他們不是重複IMO。 – 2010-12-02 14:29:55