访问列表中列表中的对象 [英] accessing an object in list in list

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

问题描述

我有一个场景,该场景是一个对象,该对象具有使用情况配置文件列表,活动列表以及一个称为设备的字段.如何从方案中访问设备?

I have a scenario which is an object which has a list of usage profiles, which has a list of activities, which has a field called equipment. how do i access equipment from scenario?

推荐答案

尝试:
Equipment myEquipment = myProfiles["my name"].Activities["my activity"].Equipment;


但是,最好在每个阶段检查空值.



但是设备是字符串.如何检查空值?"

好吧,您可以将Equipment 更改为string ...


However, it would be a good idea to check for null values at each stage.



"but equipment is a string. and how do i check for nulls?"

Well, you could change Equipment to string...

string myEquipment = myProfiles["my name"].Activities["my activity"].Equipment;



检查空值只是意味着,当您访问列表时,请确保所查找的内容存在:如果不存在,则将返回空值.如果尝试使用它访问另一个列表,则会收到对象未设置为实例..."错误.



Checking for nulls just means that when ever you access a List, you make sure that what was looked for exists: if it isn''t, then it will return a null value. If you try to use that to access another list, your will get an "object not set to an instance..." error.

string equipment = "none";
Profile p = myProfiles[0];
if (p != null)
    {
    Activity a = p.Activities[0];
    if (a != null)
        {
        equipment = a.Equipment;
        }
    }

如果要使用我在顶部建议的字符串索引版本,则需要使用字典,而不是列表.

If you want to use the string index version I suggested at the top, you will need to use a Dictionary, rather than a List.


这篇关于访问列表中列表中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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