我如何创建一个在C#中持有不同类型的字典 [英] How do I create a Dictionary that holds different types in C#
问题描述
我需要某种方式来存储键/值对其中的值可以是不同类型的。
I need some sort of way to store key/value pairs where the value can be of different types.
所以我喜欢做的事:
int i = 12;
string s = "test";
double x = 24.1;
Storage.Add("age", i);
Storage.Add("name", s);
Storage.Add("bmi", x);
和后来与检索值:
int a = Storage.Get("age");
string b = Storage.Get("name");
double c = Storage.Get("bmi");
应该如何像这样的存储样子呢?
谢谢,
埃里克
How should a Storage like this look like? Thanks, Erik
推荐答案
好了,你可以使用词典<字符串,动态>
在C#4 / .NET 4 - 但除此之外,你不能准确所示的代码做到这一点,因为没有类型,它是隐式转换为 INT
,字符串
和双击
。 (你可以写你自己的,但是你必须单独列出每种类型。)
Well, you could use Dictionary<string, dynamic>
in C# 4 / .NET 4 - but other than that, you can't do it with exactly the code shown because there's no type which is implicitly convertible to int
, string
and double
. (You could write your own one, but you'd have to list each type separately.)
您可以使用词典<字符串对象>
但随后你需要转换的结果:
You could use Dictionary<string, object>
but then you'd need to cast the results:
int a = (int) Storage.Get("age");
string b = (string) Storage.Get("name");
double c = (double) Storage.Get("bmi");
另外,你可以使获取
方法通用:
int a = Storage.Get<int>("age");
// etc
这篇关于我如何创建一个在C#中持有不同类型的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!