如何处理字典中对象的值 [英] How to process values of object within dictionary

查看:136
本文介绍了如何处理字典中对象的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

I have the following code:

Dictionary<string, object> dict= new Dictionary<string, object>();

someClass tmpClass = new someClass();

tmpClass.a = "blah";
tmpClass.b = "123";
tmpClass.c = "abc";

dict.Add("532Key", tmpClass);



//现在已经分配了键和值(字符串和对象),如何检查ley是否确实是"532Key",然后获取字典中tmpClass的值并处理对象的每个元素,将每个元素分配给类属性(让我们调用具有a,b和c作为属性的新类newClass).



// Now that the key and value (string and object) been assigned, how can I check if the ley is indeed "532Key" then get the values of tmpClass within the dictionary and process each element of the object assigning each to a class property (let call the new class newClass which have a,b, and c as properties). Thanks in advnce.

推荐答案

dict.ContainsKey可让您检查键是否存在.您可以遍历dict.Keys,然后随便查找每个值.但是,当您使用对象"时,您会很挣扎,最好的选择是使用"as"关键字遍历可能的类型列表,如果您这样做,最好强定义包含这些类型的类.使用字符串->对象会极大地使您的代码复杂化.字符串映射到someClass会更好.
dict.ContainsKey lets you check if a key exists. You can iterate over dict.Keys and then look up each value as you go. But, you will struggle when you''re using ''object'', your best bet is to use the ''as'' keyword to iterate over a list of possible types, and if you''re doing that, you''re better off strongly defining a class that contains those types. using string -> object will greatly complicate your code. string mapping to someClass would work way better.


首先,如果您知道所有值的类型都为someClass,则将其从Dictionary<string, object>更改为Dictionary<string, someClass>.要访问"532Key"的值,只需使用:
First, if you know all values are going to be of type someClass, then change it from Dictionary<string, object> to Dictionary<string, someClass>. To access the value at "532Key", just use:
var value = dict["532Key"];



(注意:如果保持原样,则需要将值转换为适当的类型,然后才能访问其任何属性!)



(Note: If you leave it as-is, you''ll need to cast value to the proper type before you can access any of it''s properties!)


这篇关于如何处理字典中对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆