如何循环遍历类的对象 [英] How can I loop through objects of a class

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

问题描述





我有像这样的普通课程的对象



Hi,

I have objects of common classes like this

public static CANBusDetails CANBusRedDetails = null;
public static CANBusDetails CANBusYellowDetails = null;
public static CANBusDetails CANBusGreenDetails = null;
public static CANBusDetails CANBusOrangeDetails = null;





我将CANBusDetails定义为类。当我试图循环通用类的对象时







I defined CANBusDetails as class. When I am trying to loop through objects of common classes


for (int i = 1; i < CANBusRedDetails.CANBusMsgIDList.Count; i++)





我得到Nullreference异常



有谁能帮我解决问题???



谢谢

John



I am getting Nullreference exception

Can anyone help me in solving the problem???

Thanks
John

推荐答案

因为您已将对象初始化为null。您需要使用 new 关键字来初始化对象。如果你有一个构造函数定义,它将被调用,成员初始化代码(如果有的话)将被执行。



目前你的对象指向null,因此你是得到一个空引用错误。
Because you have initialized the object as null. You will need to use new keyword to initialize the object. And if you have a constructor defined, it will be called and members initialization code, if any, will be executed.

Currently your object points to null and thus you are getting a null reference error.


hi
试试这样..



可能 CANBusRedDetails null ,使用以下内容来避免空引用错误

hi Try like this..

might be CANBusRedDetails is null, use the following to avoid null reference error
if( CANBusRedDetails.CANBusMsgIDList != null)
       for (int i = 1; i < CANBusRedDetails.CANBusMsgIDList.Count; i++)


您正在获取Nullreference摘要,因为该对象为空。



要遍历对象,你可以使用foreach

foreach(CAN obusded.CANBusMsgIDLi中的var obj st)

{



obj.yourObjectAttributes

...

< br $>
}





希望这会对你有所帮助。



谢谢,

Amol
you are getting Nullreference excption because the object is null.

To loop through the object, you can use foreach
foreach (var obj in CANBusRedDetails.CANBusMsgIDList)
{

obj.yourObjectAttributes
...

}


Hope this will help you.

Thanks,
Amol


这篇关于如何循环遍历类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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