避免类中方法之间的对象空引用 [英] Avoiding object null reference between methods in a class

查看:54
本文介绍了避免类中方法之间的对象空引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经进行了多年编程,但是最近我刚刚对C#熟悉,并且正在编写一个简单的游戏.我创建了一个类来编辑网格上的块.在名为Editor的此类中,我定义了< Block>列表.对象称为 块.为了识别鼠标指针悬停在的块,我定义了一个单独的块对象,称为selectedblock.

I've been programming for many years but I'm just becoming familiar with C# recently and I'm writing a simple game.  I've created a class to edit blocks on a grid.  Within this class called Editor, I've defined a list of <Block> objects called blocks.  In order to identify the block that the mouse pointer is over, I defined a separate block object called selectedblock. 

在我的Editor类Update方法中,我遍历块列表并检查鼠标指针是否悬停在一个上,如果是,则将此块分配给selectedblock标识符.然后稍后以相同的方法检查鼠标右键 单击它,如果是的话,我从阻止列表中删除了selectedblock.

In my Editor class Update method, I loop through the list of blocks and check if my mouse pointer is hovering over one, and if so, I assign this block to the selectedblock identifier.  Then later in the same method I check if the right mouse button is clicked on it, and if so, I remove selectedblock from the blocks list. 

这一切都很好,但是当我转到Draw方法并尝试使用selectedblock对象时,它返回为null.即使我将其定义为受保护的或公开的.我对于为什么从列表中引用对象的原因感到困惑 从该列表中将其删除,但是当我要访问其属性时将无法使用.我猜想我将不得不编写代码以将我想要的所有属性分别复制到该对象的新实例中.这样做有什么理由吗?

This all works fine but when I go to the Draw method, and try to use the selectedblock object it comes back as null.  Even if I define it as protected or public.  I'm confused as to why the reference to an object from a list works just fine to remove it from that list, but wont work when I want to access its properties.  I'm guessing I'd have to write code to copy all the properties I want individually to a new instance of that object.  Is there a reason why its done like this? 

推荐答案

好,我终于找到了解决方案,当我将块添加到块列表中时,我并没有初始化要尝试的属性访问,它们又返回了null.我很困惑,我不愿阅读有关使用ICloneable接口的所有知识, 甚至更加困惑.最后,我更加注意了调试器报告为null的属性.很高兴找到这种语言,就像我最初想要的那样工作,只是我很粗心. :)
Ok I finally found my solution, when I added blocks to my blocks list I wasn't initializing the properties I was trying to access and they were coming back null.  I got so confused I went off reading all about using the ICloneable interface and got even more confused.  Finally I paid closer attention to what properties the debugger was reporting as null.  Glad to find the language works as I originally wanted it to and it was just me being careless. :)


这篇关于避免类中方法之间的对象空引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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