栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C#是否可以给我一个不变的字典?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#是否可以给我一个不变的字典?

不,但是包装器很简单:

public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>{    IDictionary<TKey, TValue> _dict;    public ReadonlyDictionary(IDictionary<TKey, TValue> backingDict)    {        _dict = backingDict;    }    public void Add(TKey key, TValue value)    {        throw new InvalidOperationException();    }    public bool ContainsKey(TKey key)    {        return _dict.ContainsKey(key);    }    public ICollection<TKey> Keys    {        get { return _dict.Keys; }    }    public bool Remove(TKey key)    {        throw new InvalidOperationException();    }    public bool TryGetValue(TKey key, out TValue value)    {        return _dict.TryGetValue(key, out value);    }    public ICollection<TValue> Values    {        get { return _dict.Values; }    }    public TValue this[TKey key]    {        get { return _dict[key]; }        set { throw new InvalidOperationException(); }    }    public void Add(KeyValuePair<TKey, TValue> item)    {        throw new InvalidOperationException();    }    public void Clear()    {        throw new InvalidOperationException();    }    public bool Contains(KeyValuePair<TKey, TValue> item)    {        return _dict.Contains(item);    }    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)    {        _dict.CopyTo(array, arrayIndex);    }    public int Count    {        get { return _dict.Count; }    }    public bool IsReadonly    {        get { return true; }    }    public bool Remove(KeyValuePair<TKey, TValue> item)    {        throw new InvalidOperationException();    }    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()    {        return _dict.GetEnumerator();    }    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()    {        return ((System.Collections.IEnumerable)_dict).GetEnumerator();    }}

显然,如果要允许修改值,可以更改上面的this []设置器。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/495588.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号