亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

元組值返回 null 的字典?

元組值返回 null 的字典?

C#
蕭十郎 2023-07-22 17:02:59
我有一個類,其中的字典定義為私有成員:    Dictionary<int, (string, string)> arenaIdToSetAndNumber = new Dictionary<int, (string, string)>()     {         { 70506, ("c16", "337") },         { 70507, ("c16", "340") },         { 70508, ("c16", "343") },         { 70509, ("c16", "346") },         { 70510, ("c16", "349") },     };在調試時,我找到了與 key 相對應的項目70506,我用 2 個手表看到了這一點:我嘗試這樣做var test = arenaIdToSetAndNumber[c.grpId].Item1,并將test其設置為 null與第二塊手表中看到的一樣!我不明白為什么
查看完整描述

2 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

調試器和觀察器無法從索引器運算符 [] 推斷 Item1 是什么,因此在觀察器中將為您提供 null。但是一旦你運行代碼,它就可以很好地用于閱讀目的。為了寫作目的,您需要取出整個元組,對其進行編輯并重新插入字典中:

static?void?Main(string[]?args)
????{
????????Dictionary<int,?(string,?string)>?arenaIdToSetAndNumber?=?new?Dictionary<int,?(string,?string)>()
????????{
????????????{?70506,?("c16",?"337")?},
????????????{?70507,?("c16",?"340")?},
????????????{?70508,?("c16",?"343")?},
????????????{?70509,?("c16",?"346")?},
????????????{?70510,?("c16",?"349")?},
????????};????????var?myTuple?=?arenaIdToSetAndNumber[70509];
????????myTuple.Item1?=?"c18";
????????arenaIdToSetAndNumber[70509]?=?myTuple;
????????????????//System.Console.WriteLine(arenaIdToSetAndNumber[70509].Item1);?//?This?prints?c18
????}

否則,在一行中,只需重新創建整個元組:

arenaIdToSetAndNumber[70509]?=?("c18",?arenaIdToSetAndNumber[70509].Item2);

所有這一切都是因為 ValueTuple 是一個結構。


查看完整回答
反對 回復 2023-07-22
?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

這不使用元組,但解決了您的問題。由于您想要讀取值,請創建一個不可變的類,因此請使用屬性來檢索值。


public class Contents

{

    private readonly string leftValue;

    private readonly string rightValue;


    public Contents(string aLeftValue, string aRightValue)

    {

        leftValue = aLeftValue;

        rightValue = aRightValue;

    }


    public string LeftValue => leftValue;

    public string RightValue => rightValue;       

}

修改您的代碼以使用新類。


 Dictionary<int, Contents> arenaIdToSetAndNumber = new Dictionary<int, Contents>()

        {

            { 70506, new Contents("c16", "337") },

            { 70507, new Contents("c16", "340") },

            { 70508, new Contents("c16", "343") },

            { 70509, new Contents("c16", "346") },

            { 70510, new Contents("c16", "349") },

        };

你可以用這個來測試它。


  var content = arenaIdToSetAndNumber[70506];

  string leftValue = content.LeftValue;

  string rightValue = content.RightValue;

希望這能解決您的問題。


查看完整回答
反對 回復 2023-07-22
  • 2 回答
  • 0 關注
  • 135 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號