2017-04-01 51 views
1

我創建了一個字典,你可以看到:初始化在C#中返回溢出錯誤字典

public Dictionary<string, string> TipList 
{ 
    get { return TipList; } 
    set { TipList = value; } 
} 

我取從服務的一些數據,我希望把這些數據轉化爲我的字典裏,你可以在這裏看到:

Dictionary<string, string> dict = new Dictionary<string, string>(); 
try 
{ 
    using (var response = (HttpWebResponse)request.GetResponse()) 
    { 

     using (var reader = new StreamReader(response.GetResponseStream())) 
     { 
      var objText = reader.ReadToEnd(); 
      var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(objText).ToDictionary(x => x.Keys, x => x.Values); 
      object o; 
      object o1; 
      foreach (var item in list) 
      { 
       o = item.Value.ElementAt(0); 
       o1 = item.Value.ElementAt(1); 
       dict.Add(o.ToString(), o1.ToString()); 
      } 
      GlobalVariable.TipListCache.Add(NewCarReceiption.CSystem.Value, dict); 
      NewCarReceiption.TipList = dict.Where(i=>i.Key!=null & i.Value!=null).ToDictionary(x => x.Key, x => x.Value); 
     } 
    } 
} 

但運行我的代碼時,上述功能正試圖把自己的數據放入我的字典裏。我的應用程序將返回該錯誤後:

enter image description here

回答

3

你設置器調用TipList屬性的setter(本身),這是調用它的制定者等等 - 導致異常。

這樣的初始化:

private Dictionary<string, string> _tipList; 
public Dictionary<string, string> TipList 
{ 
    get { return _tipList; } 
    set { _tipList = value; } 
} 

或者最好的,如果您不需要默認值以外的任何行爲,與auto-implemented property

public Dictionary<string, string> TipList { get; set; } 

而且由於C#6.0,你也可以初始化它像這樣(使用自動屬性初始值設定項):

public Dictionary<string, string> TipList { get; set; } = new Dictionary<string, string>(); 
1

您一次又一次地設置相同的屬性,進入無限循環。

如果你不需要在你的getter和setter任何額外的邏輯,你可能只是讓它自動實現的:

public Dictionary<string, string> TipList 
{ 
    get; 
    set; 
} 

如果你需要在你的getter和setter更多的邏輯,你必須添加支持字段自己:

private Dictionary<string, string> tipList; 
public Dictionary<string, string> TipList 
{ 
    get 
    { 
     DoSomethingBeforeGet(); 
     return this.tipList; 
    } 
    set 
    { 
     DoSomethingBeforeSet(); 
     this.tipList = value; 
     DoSomethingAfterSet(); 
    } 
}