簡體   English   中英

在C#中初始化字典返回溢出錯誤

[英]initialize of dictionary in c# return overflow error

如您所見,我創建了一個字典:

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);
        }
    }
}

但是在運行我的代碼后,上述函數試圖將其數據放入我的字典中時。我的應用程序返回此錯誤:

在此處輸入圖片說明

您的設置程序正在調用TipList屬性的設置程序(本身),該設置程序正在調用其設置程序,依此類推-導致異常。

像這樣初始化它:

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

最好是,如果您不需要默認行為之外的其他行為,則可以使用自動實現的屬性

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

從C#6.0開始,您還可以像這樣(使用自動屬性初始化程序)對其進行初始化:

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

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

如果您在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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM