C# .NET 字典作为属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/980991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET Dictionary as a Property
提问by Anand Shah
Can someone point me out to some C# code examples or provide some code, where a Dictionary has been used as a property for a Class.
有人可以指出一些 C# 代码示例或提供一些代码,其中字典已用作类的属性。
The examples I have seen so far don't cover all the aspects viz how to declare the dictionary as property, add, remove, and retrieve the elements from the dictionary.
到目前为止,我所看到的示例并未涵盖所有方面,即如何将字典声明为属性、添加、删除和检索字典中的元素。
采纳答案by JaredPar
Here's a quick example
这是一个快速示例
class Example {
private Dictionary<int,string> _map;
public Dictionary<int,string> Map { get { return _map; } }
public Example() { _map = new Dictionary<int,string>(); }
}
Some use cases
一些用例
var e = new Example();
e.Map[42] = "The Answer";
回答by Radu094
回答by Hans Ke?ing
sample code:
示例代码:
public class MyClass
{
public MyClass()
{
TheDictionary = new Dictionary<int, string>();
}
// private setter so no-one can change the dictionary itself
// so create it in the constructor
public IDictionary<int, string> TheDictionary { get; private set; }
}
sample usage:
示例用法:
MyClass mc = new MyClass();
mc.TheDictionary.Add(1, "one");
mc.TheDictionary.Add(2, "two");
mc.TheDictionary.Add(3, "three");
Console.WriteLine(mc.TheDictionary[2]);
EDIT
编辑
When you use C# version 6 or later, you can also use this:
当您使用 C# 版本 6 或更高版本时,您还可以使用它:
public class MyClass
{
// you don't need a constructor for this feature
// no (public) setter so no-one can change the dictionary itself
// it is set when creating a new instance of MyClass
public IDictionary<int, string> TheDictionary { get; } = new Dictionary<int, string>();
}
回答by JaredPar
An example...
一个例子...
public class Example
{
public Dictionary<Int32, String> DictionaryProperty
{
get; set;
}
public Example()
{
DictionaryProperty = new Dictionary<int, string>();
}
}
public class MainForm
{
public MainForm()
{
Example e = new Example();
e.DictionaryProperty.Add(1, "Hello");
e.DictionaryProperty.Remove(1);
}
}
回答by DevinB
You could also look into indexers. (official MSDN documentation here)
您还可以查看indexers。(官方 MSDN 文档在这里)
class MyClass
{
private Dictionary<string, string> data = new Dictionary<string, string>();
public MyClass()
{
data.Add("Turing, Alan", "Alan Mathison Turing, OBE, FRS (pronounced /?tj?(?)r??/) (23 June, 1912 – 7 June, 1954) was a British mathematician, logician, cryptanalyst and computer scientist.")
//Courtesy of [Wikipedia][3]. Used without permission
}
public string this [string index]
{
get
{
return data[index];
}
}
}
Then, once you have populated the dictionary internally, you can access it's information by going
然后,一旦您在内部填充了字典,您就可以通过访问它的信息
MyClass myExample = new MyClass();
string turingBio = myExample["Turing, Alan"];
EDIT
编辑
Obviously, this has to be used carefully, because MyClass
is NOT a dictionary, and you cannot use any dictionary methods on it unless you implement them for the wrapper class. But indexers are a great tool in certain situations.
显然,这必须小心使用,因为MyClass
它不是字典,除非为包装类实现它们,否则不能在其上使用任何字典方法。但是索引器在某些情况下是一个很好的工具。
回答by Erik K.
Another example of using a dictionary as a static property with only the get accessor:
使用字典作为只有 get 访问器的静态属性的另一个示例:
private static Dictionary <string, string> dict = new Dictionary <string,string>(){
{"Design Matrix", "Design Case"},
{"N/A", "Other"}
};
public static Dictionary <string, string> Dict
{
get { return dict}
}
This structure can be used to replace values.
此结构可用于替换值。
回答by user3202856
In order to ensure the encapsulation is correct and the dictionary cannot be updated outside the class using Add or the form ExampleDictionary[1]= "test", use IReadOnlyDictionary.
为了确保封装正确并且不能在类外使用 Add 或 ExampleDictionary[1]="test" 形式更新字典,请使用 IReadOnlyDictionary。
public class Example
{
private Dictionary<int, string> exampleDictionary;
public Example()
{
exampleDictionary = new Dictionary<int, string>();
}
public IReadOnlyDictionary<int, string> ExampleDictionary
{
get { return (IReadOnlyDictionary<int, string>)exampleDictionary; }
}
}
The following code will not work, which is not the case if IDictionary is used:
以下代码将不起作用,如果使用 IDictionary,则情况并非如此:
var example = new Example();
example.ExampleDictionary[1] = test;
回答by leon22
Since .net 4.6you can also define a Dictionary like this:
从.net 4.6 开始,您还可以像这样定义字典:
private Dictionary<string,int> Values => new Dictionary<string, int>()
{
{ "Value_1", 1},
{ "Value_2", 2},
{ "Value_3", 3},
};
It's called Expression-bodied members!
这就是所谓的表情体成员!