我在公共课堂上有一个公共字典如下:
namespace ApiAssembly
{
public static class TypeStore
{
/// <summary>
/// Initializes static members of the <see cref="TypeStore"/> class.
/// </summary>
static TypeStore()
{
Store = new Dictionary<string, Type>();
}
/// <summary>
/// Gets the store.
/// </summary>
public static Dictionary<string, Type> Store { get; }
public void AddTypes()
{
// This should be allowed
TypeStore.Store.Add("object", typeof(object));
}
}
}
除了内部(通过API管理),我想阻止向此词典添加新元素。实现这一目标的最佳方法是什么?
namespace ClientAssembly
{
using ApiAssembly;
public class Client
{
public void AddTypes()
{
// How to prevent this call?
TypeStore.Store.Add("object", typeof(object));
}
}
}
Dictionnary的内容必须可公开访问,因此只需翻转访问修饰符
答案 0 :(得分:7)
您应该将实际存储字典与您用于外部世界的字典分开。一个简单的方法是:
private static Dictionary<string, Type> Storage { get; } = new Dictionary<string, Type>();
public static ReadOnlyDictionary<string, Type> Store
=> new ReadOnlyDictionary<string, Type>(Storage);
Storage
是您可以编辑的实际支持词典。
或者甚至更好,公开你想通过你的类可用的方法(它作为代理),你永远不会授予外部类访问字典本身的权限。
答案 1 :(得分:5)
将其公开为:
IReadOnlyDictionary<string, Type> dictionary = new Dictionary<string, Type>();
或另外使用ReadOnlyDictionary
包装器以防止转回Dictionary
。
完整示例:
public static class TypeStore
{
private static Dictionary<string, Type> store;
private static ReadOnlyDictionary<string, Type> storeReadOnly ;
/// <summary>
/// Initializes static members of the <see cref="TypeStore"/> class.
/// </summary>
static TypeStore()
{
store = new Dictionary<string, Type>();
storeReadOnly = new ReadOnlyDictionary<string, Type>(store);
}
/// <summary>
/// Gets the store.
/// </summary>
public static IReadOnlyDictionary<string, Type> Store => storeReadOnly;
public static void AddTypes()
{
// This should be allowed
TypeStore.store.Add("object", typeof(object));
}
}