Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

c# - Dictionary with object as value

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will not work because you have declared the dictionary as Dictionary<string, object>.

You could instead try Dictionary<string, dynamic>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...