簡體   English   中英

如果鍵不存在,則使用setter的C#自定義詞典類型

[英]C# Custom dictionary type with setter if key does not exist

我正在嘗試定義一個自定義類型,該自定義類型僅以一個差異擴展了詞典。 當我設置這樣的值時:

myCustomDic[3.5] = 4.0;

它首先檢查密鑰3.5是否存在。 如果是這樣,請將值設置為新值。 否則,它將使用新值添加密鑰。 我這樣做是這樣的:

class Dic : Dictionary<double, double>
    {
        private readonly Dictionary<double, double> _property;
        public Dic(Dictionary<double, double> property)
        {
            _property = property;
        }
        //Indexer: 
        public new double this[double CA]
        {
            get
            {
                return _property[CA];
            }
            set
            {
                if (_property.ContainsKey(CA))
                {
                    _property[CA] = value;
                }
                else
                {
                    _property.Add(CA, value);
                }
            }
        }
    }

我這樣使用它:

var testDic = new Dic(new Dictionary<double, double>());
testDic[2.5] = 4.0;

但是,沒有將鍵和值對添加到testDic嗎? 有人可以告訴為什么嗎?

因為您是Dictionary的子類,所以您也不需要自己的私有Dictionary。 另外,您描述的行為是Dictionary已如何工作,因此您根本不需要創建自己的類:

var t2 = new Dictionary<double, double>();

t2[2.5] = 4.0;
Console.WriteLine(t2[2.5]);  // outputs 4
t2[2.5] = 8.0;
Console.WriteLine(t2[2.5]);  // outputs 8

Dictionary<TKey, TValue>.Item Property (TKey)的文檔中:

設置屬性值時,如果鍵在詞典中,則與該鍵關聯的值將由分配的值替換。 如果鍵不在詞典中,則將鍵和值添加到詞典中。

但是你可以:

class Dic : Dictionary<double, double> {
    //Indexer: 
    public new double this[double CA] {
        get => (this as Dictionary<double, double>)[CA];
        set {
            var parent = this as Dictionary<double, double>;
            if (parent.ContainsKey(CA))
                parent[CA] = value;
            else
                parent.Add(CA, value);
        }
    }
}

然后,您可以執行以下操作:

var testDic = new Dic();

testDic[2.5] = 4.0;
Console.WriteLine(testDic[2.5]); // this outputs 4
testDic[2.5] = 8.0;
Console.WriteLine(testDic[2.5]);  // this outputs 8

這是因為您檢查了Count屬性,該屬性仍為零,因為您沒有覆蓋它。

您的_property的數量會增加,但外部的數量不會增加。

調試器可視化器仍將調用原始詞典計數,該計數仍將報告為0,但如果將其打印到控制台,它將起作用。

我仍然不明白為什么您從詞典中派生,因為描述要求的方式已經由詞典實現。

public TValue this[TKey key]
{
    get
    {
        int num = this.FindEntry(key);
        if (num >= 0)
        {
            return this.entries[num].value;
        }
        ThrowHelper.ThrowKeyNotFoundException();
        return default(TValue);
    }
    set
    {
        this.Insert(key, value, false);
    }
}

暫無
暫無

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

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