如何以返回的字典无法更改的方式创建字典的访问器 C# / 2.0

发布于 2024-08-27 13:55:00 字数 1178 浏览 8 评论 0原文

我想到了下面的解决方案,因为集合非常非常小。但如果它很大呢?

private Dictionary<string, OfTable> _folderData = new Dictionary<string, OfTable>();

public Dictionary<string, OfTable> FolderData
{
    get { return new Dictionary<string,OfTable>(_folderData); }
}

使用 List,您可以做出:

public class MyClass
{
    private List<int> _items = new List<int>();

    public IList<int> Items
    {
        get { return _items.AsReadOnly(); }
    }
}

那太好了!

预先感谢,干杯& BR - Matti

现在当我认为集合中的对象位于堆中时。所以我的解决方案不会阻止调用者修改它们!导致两个字典都包含对同一对象的引用。这是否适用于上面的列表示例?

class OfTable
{
    private int _table;
    private List<int> _classes;
    private string _label;

    public OfTable()
    {
        _classes = new List<int>();
    }

    public int Table
    {
        get { return _table; }
        set { _table = value; }
    }

    public List<int> Classes
    {
        get { return _classes; }
        set { _classes = value; }
    }

    public string Label
    {
        get { return _label; }
        set { _label = value; }
    }
}

那么如何使其不可变呢?

I thought of solution below because the collection is very very small. But what if it was big?

private Dictionary<string, OfTable> _folderData = new Dictionary<string, OfTable>();

public Dictionary<string, OfTable> FolderData
{
    get { return new Dictionary<string,OfTable>(_folderData); }
}

With List you can make:

public class MyClass
{
    private List<int> _items = new List<int>();

    public IList<int> Items
    {
        get { return _items.AsReadOnly(); }
    }
}

That would be nice!

Thanks in advance, Cheers & BR - Matti

NOW WHEN I THINK THE OBJECTS IN COLLECTION ARE IN HEAP. SO MY SOLUTION DOES NOT PREVENT THE CALLER TO MODIFY THEM!!! CAUSE BOTH Dictionary s CONTAIN REFERENCES TO SAME OBJECT. DOES THIS APPLY TO List EXAMPLE ABOVE?

class OfTable
{
    private int _table;
    private List<int> _classes;
    private string _label;

    public OfTable()
    {
        _classes = new List<int>();
    }

    public int Table
    {
        get { return _table; }
        set { _table = value; }
    }

    public List<int> Classes
    {
        get { return _classes; }
        set { _classes = value; }
    }

    public string Label
    {
        get { return _label; }
        set { _label = value; }
    }
}

so how to make this immutable??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心的憧憬 2024-09-03 13:55:00

推出您自己的 ReadOnlyDictionary 包装类并不困难。像这样的事情:

public sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    private readonly IDictionary<TKey, TValue> _dictionary;

    public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");

        _dictionary = dictionary;
    }

    public bool ContainsKey(TKey key)
    {
        return _dictionary.ContainsKey(key);
    }

    public int Count
    {
        get { return _dictionary.Count; }
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return _dictionary.GetEnumerator();
    }

    public ICollection<TKey> Keys
    {
        get { return _dictionary.Keys; }
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        return _dictionary.TryGetValue(key, out value);
    }

    public ICollection<TValue> Values
    {
        get { return _dictionary.Values; }
    }

    public TValue this[TKey key]    // Item
    {
        get { return _dictionary[key]; }
    }

    #region IDictionary<TKey, TValue> Explicit Interface Implementation

    void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
    {
        throw new NotSupportedException("Dictionary is read-only.");
    }

    bool IDictionary<TKey, TValue>.Remove(TKey key)
    {
        throw new NotSupportedException("Dictionary is read-only.");
    }

    TValue IDictionary<TKey, TValue>.this[TKey key]    // Item
    {
        get { return _dictionary[key]; }
        set { throw new NotSupportedException("Dictionary is read-only."); }
    }

    #endregion

    #region ICollection<T> Explicit Interface Implementation

    void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
    {
        throw new NotSupportedException("Collection is read-only.");
    }

    void ICollection<KeyValuePair<TKey, TValue>>.Clear()
    {
        throw new NotSupportedException("Collection is read-only.");
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
    {
        return _dictionary.Contains(item);
    }

    void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        _dictionary.CopyTo(array, arrayIndex);
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
    {
        get { return true; }
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
    {
        throw new NotSupportedException("Collection is read-only.");
    }

    #endregion

    #region IEnumerable Explicit Interface Implementation

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable)_dictionary).GetEnumerator();
    }

    #endregion
}

如果您使用 C#3 或更高版本,那么您也可以敲出匹配的 AsReadOnly 扩展方法:

public static class ReadOnlyDictionaryHelper
{
    public static ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
    {
        var temp = dictionary as ReadOnlyDictionary<TKey, TValue>;
        return temp ?? new ReadOnlyDictionary<TKey, TValue>(dictionary);
    }
}

然后从您的属性返回只读包装器:

// in C#2
return new ReadOnlyDictionary<string, OfTable>(_folderData);

// in C#3 or later
return _folderData.AsReadOnly();

It's not difficult to roll your own ReadOnlyDictionary<K,V> wrapper class. Something like this:

public sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    private readonly IDictionary<TKey, TValue> _dictionary;

    public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
    {
        if (dictionary == null)
            throw new ArgumentNullException("dictionary");

        _dictionary = dictionary;
    }

    public bool ContainsKey(TKey key)
    {
        return _dictionary.ContainsKey(key);
    }

    public int Count
    {
        get { return _dictionary.Count; }
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return _dictionary.GetEnumerator();
    }

    public ICollection<TKey> Keys
    {
        get { return _dictionary.Keys; }
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        return _dictionary.TryGetValue(key, out value);
    }

    public ICollection<TValue> Values
    {
        get { return _dictionary.Values; }
    }

    public TValue this[TKey key]    // Item
    {
        get { return _dictionary[key]; }
    }

    #region IDictionary<TKey, TValue> Explicit Interface Implementation

    void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
    {
        throw new NotSupportedException("Dictionary is read-only.");
    }

    bool IDictionary<TKey, TValue>.Remove(TKey key)
    {
        throw new NotSupportedException("Dictionary is read-only.");
    }

    TValue IDictionary<TKey, TValue>.this[TKey key]    // Item
    {
        get { return _dictionary[key]; }
        set { throw new NotSupportedException("Dictionary is read-only."); }
    }

    #endregion

    #region ICollection<T> Explicit Interface Implementation

    void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
    {
        throw new NotSupportedException("Collection is read-only.");
    }

    void ICollection<KeyValuePair<TKey, TValue>>.Clear()
    {
        throw new NotSupportedException("Collection is read-only.");
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
    {
        return _dictionary.Contains(item);
    }

    void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        _dictionary.CopyTo(array, arrayIndex);
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
    {
        get { return true; }
    }

    bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
    {
        throw new NotSupportedException("Collection is read-only.");
    }

    #endregion

    #region IEnumerable Explicit Interface Implementation

    IEnumerator IEnumerable.GetEnumerator()
    {
        return ((IEnumerable)_dictionary).GetEnumerator();
    }

    #endregion
}

If you're using C#3 or later then you could knock-up a matching AsReadOnly extension method too:

public static class ReadOnlyDictionaryHelper
{
    public static ReadOnlyDictionary<TKey, TValue> AsReadOnly<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
    {
        var temp = dictionary as ReadOnlyDictionary<TKey, TValue>;
        return temp ?? new ReadOnlyDictionary<TKey, TValue>(dictionary);
    }
}

And then return the read-only wrapper from your property:

// in C#2
return new ReadOnlyDictionary<string, OfTable>(_folderData);

// in C#3 or later
return _folderData.AsReadOnly();
请你别敷衍 2024-09-03 13:55:00

使用 ReadOnlyCollection类。

ReadOnlyCollection 泛型类的实例始终是只读的。只读集合只是带有防止修改集合的包装器的集合;因此,如果对基础集合进行更改,只读集合会反映这些更改。请参阅 Collection 以获取此类的可修改版本。

--编辑--

签出这里是简单的字典包装。以及 Richard Carr 的通用只读词典

Use ReadOnlyCollection<T> class.

An instance of the ReadOnlyCollection generic class is always read-only. A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes. See Collection for a modifiable version of this class.

--EDIT--

Checkout a trivial dictionary wrapper here. And A Generic Read-Only Dictionary by Richard Carr.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文