我在公共(public)类(class)中有一个公共(public)词典如下:
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 的内容必须是可公开访问的,所以仅仅翻转访问修饰符不是一个选项
最佳答案
您应该将实际存储字典与您用于外部世界的字典分开。一个简单的方法是:
private static Dictionary<string, Type> Storage { get; } = new Dictionary<string, Type>();
public static ReadOnlyDictionary<string, Type> Store
=> new ReadOnlyDictionary<string, Type>(Storage);
Storage
是您可以编辑的实际支持字典。
或者更好的是,公开您希望通过您的类(它充当代理)可用的方法,您永远不会授予外部类访问字典本身的权限。
关于c# - 防止添加到公共(public)词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49387852/