简体   繁体   English

字典值C#

[英]Dictionary value c#

A dictionary cannot be changed if we are looping over it in .Net. 如果我们在.Net中循环访问字典,则无法更改。 But why is the value in a dictionary read only. 但是为什么字典中的值是只读的。 Any one has any ideas ?. 任何人有任何想法吗? Why .Net team decided on not changing the value when looping over dictionary. 为什么.Net团队决定在遍历字典时不更改值。 I can understand if the key cannot be changed but why value ?. 我能理解密钥是否不能更改,但为什么要值? Also if you are using LINQ and getting the keys back in form of Ienumerable, can the value be changed ?. 另外,如果您正在使用LINQ并以Ienumerable的形式取回密钥,则可以更改该值吗? does lazy loading have a role to play ? 延迟加载有作用吗?

Why did the BCL team decide on not allowing changes to the value when looping over dictionary. 为什么BCL团队决定在循环字典时不允许更改 I understand that the key cannot be changed but why not allow changes to the value? 我知道密钥不能更改,但是为什么不允许更改值呢?

I cannot speak definitively for the team which built the dictionary, but I can make some educated guesses . 我不能确切地为创建字典的团队说些什么,但是我可以做出一些有根据的猜测

First, it is often said that good programs are strict about the correctness of their outputs, but forgiving in what they accept. 首先,经常有人说,好的程序对输出的正确性要求严格,但是却宽容了它们接受的内容。 I do not believe this to be a good design principle. 我认为这不是一个好的设计原则。 This is a bad design principle because it allows buggy callers to take dependencies on undefined and unsupported behaviour. 这是一个糟糕的设计原则,因为它允许错误的调用者 依赖 未定义不受支持的行为。 It thereby creates a backwards-compatibility burden. 因此,这产生了向后兼容的负担。 (We certainly see this in the web browser world, where every browser vendor is pressured to be compatible with every other browser's acceptance of incorrect HTML.) (我们肯定在Web浏览器世界中看到了这一点,在该世界中,每个浏览器供应商都被迫与其他所有浏览器接受的错误HTML兼容。)

Components define contracts -- they say what information they accept as input, what operations they support, and what results they produce. 组件定义合同-他们说接受什么信息作为输入,支持什么操作以及产生什么结果。 When you accept inputs that are not in your contract, or support operations that are not in your contract, what you're doing is essentially making a new contract, a contract which is not documented, not supported, and could be broken in a future version. 当您接受合同中未包含的输入内容或支持合同中不包含的操作时,您正在做的实际上是签订合同,该合同没有记录,不受支持并且将来可能会被破坏版。 You're basically building a time bomb and when it goes off, either a customer (who probably didn't even know that they were doing something unsupported) gets broken, or the component provider ends up having to support forever a contract that they didn't actually sign up for. 您基本上是在建造定时炸弹,当定时炸弹熄灭时,要么客户(可能甚至不知道他们在做不受支持的事情)崩溃,要么组件提供商最终不得不永远支持他们没有做过的合同实际上没有注册。

It is therefore a good design principle to strictly enforce your contract . 因此, 严格执行合同是一个好的设计原则。 The contract of IEnumerable on a collection is "it's illegal to modify the collection while iterating". 集合上的IEnumerable合同“在迭代时修改集合是非法的”。 An implementer of this contract can choose to say "well, I happen to know that certain modifications are safe, so I'll allow those", and hey, suddenly you're not implementing the contract anymore. 该合同的实施者可以选择说“好吧,我碰巧知道某些修改是安全的,所以我会允许这些修改”,嘿,突然之间,您不再执行该合同。 You're implementing a different, undocumented contract that people will come to rely on. 您正在执行另一种无证的合同,人们会依赖该合同。

It is better to simply enforce the contract, even if that's unnecessary. 最好只是执行合同,即使那是不必要的。 That way, in the future, you have the freedom to rely upon your documented contract without worrying that some caller has broken the contract and gotten away with it, and expects to continue to be able to do so forever. 这样一来,将来您就可以自由地依赖已记录在案的合同,而不必担心某些呼叫者违反了该合同并放弃了该合同,并希望它能够永远永远如此。

It would be easy to design a dictionary that allowed mutation of values during iteration. 设计一个允许在迭代过程中发生值突变的字典会很容易。 Doing so prevents the component providers from ever being able to turn that feature off, and they are not required to provide it, so it is better to give an error when someone tries than to allow a caller to violate the contract. 这样做会阻止组件提供程序永远关闭该功能,并且不需要提供这些功能,因此在有人尝试时给出错误比允许调用者违反合同更好。

Second guess: the dictionary type is unsealed, and therefore can be extended. 第二个猜测:字典类型未密封,因此可以扩展。 Third parties might extend the dictionary in such a manner that their invariants would be violated if a value were changed during an enumeration. 如果在枚举过程中更改了值,则第三方可能会扩展字典,从而违反其不变式。 Suppose, for example, that someone extends a dictionary in such a manner that it can be enumerated sorted by value . 例如,假设某人以一种可以按value枚举的方式扩展字典。

When you write a method that takes a Dictionary and does something to it, you assume that the operation will work on all dictionaries , even third party extensions. 当您编写一个接受Dictionary并对其执行操作的方法时,您会假定该操作将对所有词典 ,甚至第三方扩展都适用。 The designers of a component that is intended for extension need to be even more careful than usual to ensure that the object enforces its contract, because unknown third parties might be relying upon the enforcement of that contract. 打算进行扩展的组件的设计人员需要比平时更加​​小心,以确保对象执行其合同,因为未知的第三方可能依赖于该合同的执行。 Because there might be a dictionary that cannot support changing a value during iteration, the base class should not support it either; 因为可能有一个字典支持在迭代过程中更改值,所以基类也不应该支持它。 to do otherwise is to violate the substitutability of derived classes for base classes. 否则将违反派生类对基类的替代性。

Also if you are using LINQ and getting the keys back in form of IEnumerable, can the value be changed ? 另外,如果您正在使用LINQ并以IEnumerable的形式获取密钥,那么可以更改该值吗?

The rule is that a dictionary may not be changed while iterating over it. 规则是字典在迭代时不得更改。 Whether you're using LINQ to do the iteration or not is irrelevant; 是否使用LINQ进行迭代都无关紧要; iteration is iteration. 迭代就是迭代。

does lazy loading have a role to play? 延迟加载有作用吗?

Sure. 当然。 Remember, defining a LINQ query does not iterate over anything; 请记住,定义LINQ查询不会对任何内容进行迭代。 the result of a query expression is a query object. 查询表达式的结果是查询对象。 It is only when you iterate over that object that the actual iteration happens over the collection. 只有当您遍历该对象时,实际迭代才会发生在集合上。 When you say: 当你说:

var bobs = from item in items where item.Name == "Bob" select item;

no iteration happens here. 这里没有迭代发生。 It's not until you say 直到你说

foreach(var bob in bobs) ...

that iteration over items happens. 发生在项目上的迭代。

A KeyValuePair is a struct and mutable structs are evil, so it has been made read-only. KeyValuePair是一个结构,可变结构是邪恶的,因此已将其设置为只读。

To change some values, you can iterate over the KeyValuePairs and store all the updates you want to make. 要更改某些值,可以遍历KeyValuePairs并存储要进行的所有更新。 When you have finished iterating you can then loop over your list of updates and apply them. 完成迭代后,您可以遍历更新列表并应用它们。 Here's an example of how you could do it (without using LINQ): 这是一个如何做的示例(不使用LINQ):

    Dictionary<string, string> dict = new Dictionary<string,string>();
    dict["foo"] = "bar";
    dict["baz"] = "qux";

    List<KeyValuePair<string, string>> updates = new List<KeyValuePair<string,string>>();
    foreach (KeyValuePair<string, string> kvp in dict)
    {
        if (kvp.Key.Contains("o"))
            updates.Add(new KeyValuePair<string, string>(kvp.Key, kvp.Value + "!"));
    }

    foreach (KeyValuePair<string, string> kvp in updates)
    {
        dict[kvp.Key] = kvp.Value;
    }

I am not sure why but you could work around this limitation by indirectly referencing values. 我不确定为什么,但是您可以通过间接引用值来解决此限制。 For example, you could create a class that simply references another like this: 例如,您可以创建一个仅引用另一个这样的类:

class StrongRef<ObjectType>
{
    public StrongRef(ObjectType actualObject)
    {
        this.actualObject = actualObject;
    }

    public ObjectType ActualObject
    {
        get { return this.actualObject; }
        set { this.actualObject = value; }
    }

    private ObjectType actualObject;
}

Then, instead altering the values in the dicitonary you could alter the indirect reference. 然后,您可以更改间接参考,而不必更改二分法中的值。 (I've heard it on good authority that the following routine is used by Blue Peter to replace their dead dogs with identical looking live animals.) (我听说过,Blue Peter使用以下例程用外观相同的活体动物代替死狗)。

public void ReplaceDeadDogs()
{
    foreach (KeyValuePair<string, StrongRef<Dog>> namedDog in dogsByName)
    {
        string name = namedDog.Key;
        StrongRef dogRef = namedDog.Value;

        // update the indirect reference
        dogRef.ActualObject = PurchaseNewDog();
    }
}

Other alternatives would be to record the changes necessary in a second dictionary when iterating and then applying these changes afterwards (by iterating the second dicitonary), or to build a complete replacement dictionary whilst iterating and using this instead of the original after completing the loop. 其他替代方法是在迭代时将必要的更改记录在第二个字典中,然后再应用这些更改(通过迭代第二个数字),或者在迭代并构建完一个完整的替换字典后再使用此字典而不是原始字典。

From the this Microsoft support reply (based on Hashtable but the same applies) 从此Microsoft支持回复 (基于Hashtable但同样适用)

The key here is that enumerators are designed to provide a snapshot of the entire collection, but for performance reasons they don't copy the entire collection to another temporary array or anything like that. 这里的关键是枚举器旨在提供整个集合的快照,但是出于性能原因,它们不会将整个集合复制到另一个临时数组或类似的东西。 Instead they use the live collection and throw an exception if they detect someone changed the collection. 相反,他们使用实时集合并在检测到有人更改集合时抛出异常。 Yes, it makes this type of code harder to write... 是的,它使这种类型的代码更难编写...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM