c# - 防止添加到公共(public)词典

标签 c#

我在公共(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/

相关文章:

c# - 什么是NullReferenceException,如何解决?

c# - C#从URL中提取域名

c# - WP8 应用程序中具有 WCF 服务的凭据

c# - 序列化字节数组与 XML 文件

c# - 在安装包期间如何通过 Sitecore API 导入序列化项目?

C#:IFormattable、IFormatProvider 和 ICustomFormatter 之间的连接,以及何时使用什么

c# - 这里需要线程安全代码吗?

c# - C# 方法可以返回一个方法吗?

c# - 如果 1 列包含相同数据,SQL 追加其他列

c# - SoapHttpClientProtocol 收到意外的内容类型