简体   繁体   中英

Dictionary value c#

A dictionary cannot be changed if we are looping over it in .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. 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 ?. 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. 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.)

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". 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 .

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. 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 ?

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; iteration is iteration.

does lazy loading have a role to play?

Sure. Remember, defining a LINQ query does not iterate over anything; 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.

To change some values, you can iterate over the KeyValuePairs and store all the updates you want to make. 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):

    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.)

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)

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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