字典与对象作为值 [英] Dictionary with object as value
问题描述
我正在尝试创建一个 code>一个字符串为key,一个匿名对象为值。或者,实际上我不只是在尝试,我在做。
但是当我想改变对象中的一个特定参数时,它会出错。
我声明这样的字典:
var areas = new Dictionary< string,object>
{
{Key1,new {name =Name1,today = 0,all = 0}},
{Key2,new {name =Name2 = 0,all = 0}},
...
}
然后我假设我可以这样做:
foreach(region中的var area.Keys.ToArray())
{
var areaname = areas [area] .name;
}
但Visual Studio不同意,拒绝编译。如果我写这个,那么一切都按照我的想法工作 - 但是这并不能帮助我,只是让我更沮丧。
var areaname = new
{
name =Nametest,today = 0,all = 0
};
var testname = areaname.name;
我做错了什么?为什么不为我工作?这是不可能的吗?
感谢所有的答案,他们肯定清除了一些东西!
我想我可能会混淆类型对象与对象的想法,即C#中的类,沮丧。我会重新考虑整个设计业务,可能会做一些完全不同的工作,而不是使用恶劣的解决方案。虽然有趣,但我不认为我与C#的关系已经发展得如此之远!
工作是因为你已经将字典声明为 Dictionary< string,object>
。
你可以试试字典< string,dynamic>
。
I'm going nuts here. It's probably because I've missed some rule, but if so, then please tell me.
I'm trying to create a Dictionary
with a string for key and an anonymous object as value. Or, actually I'm not just trying, I'm doing it.
But when I want to alter a specific parameter in the object, it goes wrong.
I declare the dictionary like this:
var areas = new Dictionary<string, object>
{
{"Key1", new {name = "Name1", today = 0, all = 0}},
{"Key2", new {name = "Name2", today = 0, all = 0}},
...
}
And then I'm assuming I can do this:
foreach (var area in areas.Keys.ToArray())
{
var areaname = areas[area].name;
}
but Visual Studio does not agree, and refuses to compile. If I write this, though, everything works as I would think - but that doesn't really help me out, it's just making me more frustrated.
var areaname = new
{
name = "Nametest", today = 0, all = 0
};
var testname = areaname.name;
What am I doing wrong? Why isn't it working for me? Is it simply impossible to do so?
Thanks for all your answers, they surely cleared things up a bit! I think I might have been confusing the type object with the idea of objects, that is classes, in C# out of frustration. I'll rethink the whole design business and probably do something completely different instead of using evil or dirty solutions. Though interesting, I don't think my relationship with C# has evolved that far yet!
This will not work because you have declared the dictionary as Dictionary<string, object>
.
You could instead try Dictionary<string, dynamic>
.
这篇关于字典与对象作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!