如何以返回的字典无法更改的方式创建字典的访问器 C# / 2.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
推出您自己的
ReadOnlyDictionary
包装类并不困难。像这样的事情:如果您使用 C#3 或更高版本,那么您也可以敲出匹配的
AsReadOnly
扩展方法:然后从您的属性返回只读包装器:
It's not difficult to roll your own
ReadOnlyDictionary<K,V>
wrapper class. Something like this:If you're using C#3 or later then you could knock-up a matching
AsReadOnly
extension method too:And then return the read-only wrapper from your property:
使用
ReadOnlyCollection
类。--编辑--
签出这里是简单的字典包装。以及 Richard Carr 的通用只读词典。
Use
ReadOnlyCollection<T>
class.--EDIT--
Checkout a trivial dictionary wrapper here. And A Generic Read-Only Dictionary by Richard Carr.