简体   繁体   中英

How to write Python 3 dictionary in C# .Net Framework 4.6 WPF App

I'm new to C# and the .Net Framework 4.6. I do know Python, and I was wondering how to do something like this Python dictionary in C#:

GameData = {"VP":0, "Hamsters":"yes"};

I've already looked into C# dictionaries and arrays, that's not what I'm looking for. I want something that can be retrieved by something like this:

GameData["Hamsters"];
// Returns "yes"

Welcome to c#. Strong typing is a bitch. You do want a dictionary, but you need to specify the types of the key and value in the key value pairs during the instantiation of said dictionary. In your case, its string, and string.

Dictionary<string, string> yourDictionary = new Dictionary<string, string>();

Passing in these types in angle brackets after the type name is called generics in c#.

You can use the keyword 'var' to assume the implied type. Sometimes the implied type cannot be determined, and you must specify a type on the left hand side of the assignment operator. Thats not the case here though.

var yourDictionary = new Dictionary<string, string>();

You can also use a block at the end of the constructor to specify attributes or properties about the object.

var yourDictionary = new Dictionary<string, string>()
{
  {"aKey", "aValue"},
  {"anotherKey", "anotherValue"} 
};

Now you should be able to access the values with

yourDictionary["aKey"];

and

yourDictionary["anotherKey"];

Careful though, because trying to get a key thats not there will throw an exception. Adding a duplicate key will also throw an exception. You can put the get calls in a try catch block

try{
  yourDictionary["anotherKey"];
}
catch(Exception ex){
  //do something with the error here
}

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