使字典只读在C# [英] Make dictionary read only in C#

查看:1650
本文介绍了使字典只读在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典< string,List< string>> ,并希望将成员公开为只读。我看到我可以返回它作为 IReadOnlyDictionary< string,List< string>> ,但我不知道如何返回它作为 IReadOnlyDictionary< string,IReadOnlyList< string>>

I have a Dictionary<string, List<string>> and would like to expose the member as read only. I see that I can return it as a IReadOnlyDictionary<string, List<string>>, but I can't figure out how to return it as an IReadOnlyDictionary<string, IReadOnlyList<string>>.

有办法吗?在c ++中我只是使用const,但C#没有这个。

Is there a way to do this? In c++ I'd just be using const, but C# doesn't have that.

注意,只需使用 IReadOnlyDictionary 在这种情况下没有帮助,因为我想要的值也只读。看来唯一的方法是创建另一个IReadOnlyDictionary,并添加IReadOnlyList给他们。

Note that simply using a IReadOnlyDictionary does not help in this case, because I want the values to be read only as well. It appears the only way to do this is build another IReadOnlyDictionary, and add IReadOnlyList to them.

另一个选项,我不会很兴奋,将创建包装器,它实现了接口IReadOnlyDictionary>,并且它拥有原始实例的副本,但似乎过分。

Another option, which I wouldn't be thrilled with, would be to create wrapper which implements the interface IReadOnlyDictionary>, and have it hold a copy of the original instance, but that seems overkill.

推荐答案

将像将字典引用 IReadOnlyDictionary< string,IReadOnlyList< string>> 一样简单,因为 Dictionary< TKey,TValue> implements IReadOnlyDictionary< TKey,TValue>

It would be as easy as casting the whole dictionary reference to IReadOnlyDictionary<string, IReadOnlyList<string>> because Dictionary<TKey, TValue> implements IReadOnlyDictionary<TKey, TValue>.

希望 List< string> 值为 IReadOnlyList< string>

所以你需要这样的:

var readOnlyDict = (IReadOnlyDictionary<string, IReadOnlyList<string>>)dict.ToDictionary(pair => pair.Key, pair.Value.AsReadOnly());



不可改写的字典



建议,但如果您要查找不可变的字典,请添加 系统.Collections.Immutable NuGet包到您的解决方案,您就可以使用它们:

Immutable dictionaries

This is just a suggestion, but if you're looking for immutable dictionaries, add System.Collections.Immutable NuGet package to your solution and you'll be able to use them:

// ImmutableDictionary<string, ImmutableList<string>>
var immutableDict = dict.ToImmutableDictionary(pair => pair.Key, pair.Value.ToImmutableList());

进一步了解不可变的集合

这篇关于使字典只读在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆