Can I use dot notation to access dictionary values?

I use it Dictionary<string, string>as a configuration for tools, and it would be easier for my users not to know about programming in order to be able to get autocomplete from Visual Studio.

In Python, I can make a dictionary and access various values ​​using a point operator.

d = {'name':'Joe', 'mood':'grumpy'}
d.name
d.mood

Does C # have a way to do this?

I understand all the problems associated with the fact that the dictionary is just a general collection (how general? Is it just a list of interesting KeyValuePairs questions). I am not going to write a wrapper class for this to execute it (I would like it to be a little more flexible than using explicit properties with a custom class).

+5
source share
4

# :

var d = new { name = "Joe", mood = "grumpy"};
d.name
d.mood

:

var d = new Person { Name = "Joe", Mood = "grumpy"};
d.Name
d.Mood

# 4.0 DLR, ExpandoObject:

dynamic d = new ExpandoObject();
d.name = "Joe";
d.mood = "grumpy";

, IntelliSense, #.

#, , ,

var d = new Dictionary<string, string()
    { { "name", "Joe" }, { "mood", "grumpy" } };
d["name"]
d["mood"]

IntelliSense.

API, .

+4

imo-.

- ?

- ( ) , - . n (1) .

public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
    IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback

-://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/589059d3-d7f8-e09b-705d-91a461971cc2.htm

, , - .

linq - ,

moodyPerson p = new moodyPerson{mood = "good", name="jim"};

.

intellisense, . , .

0

Do not go into a complicated solution with ExpandoObject () if you plan to instantiate your objects at runtime (for example, from a database call), there is no intellisense for dot notation, and this will lead to a compilation error if you try to use it. you can use the "propname"] notation to access them, however at this point you could also create custom class objects or just manipulate the values ​​as needed in a DataTable ()

0
source

All Articles