2017-04-01 55 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(); 
    } 
}