【问题标题】:Accessing private Dictionary访问私人词典
【发布时间】:2012-03-04 12:05:39
【问题描述】:

我们有一个带有公开字典的类:

public class SomethingWithADictionary {
    public Dictionary<string, Instance> Instances { get; set; } 
}

目前我们直接访问这个字典,像这样:

Instance inst = a.Instances["key"];

我们希望将字典设为私有,但有一种公共方式可以使用相同的索引器语法访问字典元素。原因是,如果实例不在字典中,我们希望采取一些措施而不是仅仅抛出错误。

你是怎么做到的?

【问题讨论】:

    标签: c#


    【解决方案1】:

    它必须是 完全 相同的语法吗?如果您不介意以以下方式访问它:

    Instance inst = a["key"];
    

    那么很简单——你只需添加一个索引器:

    public class SomethingWithADictionary {
        private Dictionary<string, Instance> instances = 
            new Dictionary<string, Instance>();
    
        public Instance this[string key]
        {
            get
            {
                Instance instance;
                if (!instances.TryGetValue(key, out instance))
                {
                    // Custom logic here
                }
                return instance;
            }
            // You may not even want this...
            set { instances[key] = value; }
        }
    }
    

    【讨论】:

    • 这种语法更好。我可以更改来电者。
    • TryGetValue 慢吗?我们经常这样做。在吸气剂内部,以正常方式获取它并捕获任何异常会更好吗?处理异常的开销不是问题 - 这些将非常罕见。
    • @OldMan:你为什么希望它慢一点?它肯定比在异常情况下捕获异常要快,而且它也比使用 ContainsKey 检查然后使用索引器要快。我希望性能与索引器几乎完全相同 - 事实上,如果索引器是使用 TryGetValue 实现的,我一点也不感到惊讶。当然,如果您有任何性能问题,那么正确的方法是测试
    【解决方案2】:

    Indexed property 是要走的路。 应该这样做:

    public class SomethingWithADictionary {
        private Dictionary<string, Instance> Instances { get; set; } 
        [System.Runtime.CompilerServices.IndexerNameAttribute("Instances")]
        public  Instance this [String skillId]{
          // Add getters and setters to manipulate Instances dictionary 
        }
    }
    

    【讨论】:

    • C# 不使用 IndexerNameAttribute,因此仍然不允许使用 C# 作为 a.Instances["foo"] 访问它。您还公开了该字段,目前甚至无法编译,因为您有两个名为“Instances”的成员。
    • @JonSkeet 谢谢,刚刚编辑了我的代码。那么谁在使用IndexerNameAttribute?知道为什么即使编译器不使用它仍然可用吗?
    猜你喜欢
    • 2015-02-17
    • 2010-10-15
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 2013-02-13
    • 2013-03-24
    • 2012-06-04
    • 1970-01-01
    相关资源
    最近更新 更多