将变量设置为"Nothing"(无).是一个好习惯吗? [英] Set variables to "Nothing" is a good practice?

查看:95
本文介绍了将变量设置为"Nothing"(无).是一个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

Dim myRect As Rectangle = New Rectangle(0,0,100,100)

必需还是只是 fine 以后再执行此操作:

Is it necessary or just fine to later do this:

myRect = Nothing

还是没有必要?谢谢.

如果是必要的,还有其他情况不是我的变量所需要的吗?

IF it is necessary, are there other cases it isn't for my variables?

推荐答案

通常,作为

In general, as Joel said, it's unnecessary.

不过,在您的特定示例中,它实际上是毫无意义的. Rectangle值类型,因此将其设置为Nothing不会影响对象的引用计数.它将为您的myRect变量分配一个新的(Rectangle的默认值).这类似于在方法末尾具有Integer变量并将其设置为0的情况.什么都没买.

In your specific example, though, it is actually pointless. Rectangle is a value type, so setting it to Nothing is not even affecting an object's reference count; it's assigning a new value (the default value for Rectangle) to your myRect variable. This is analogous to having an Integer variable and setting it to 0 at the end of a method. Doesn't buy you anything.

我应该指出,在C#中将任何变量设置为Nothing [或null"永远不会完成任何事情"的说法是一个神话.如果不再需要引用的对象,但您仍然具有对类实例本身的引用,则很有可能在一个类中有一个 field ,也可以将其设置为null.

I should point out that the claim "Setting any variable to Nothing [or null in C#] never accomplishes anything"* is a myth. It is entirely possible that you may have a field in a class which you might as well set to null if the object referenced is no longer needed but you still have a reference to the class instance itself.

作为一个简单的示例,假设您有一些包装了T[]数组的容器类,并且为该容器提供了Empty方法.在此方法中将容器的内部数组设置为null可能是有意义的,这将导致对该数组对象的零引用,使其有资格进行垃圾回收. (然后,当外部代码下一次尝试向集合中添加T时,您将创建一个新数组.)如果您未在Empty上将该字段设置为null,那么仍然会有对该数组的引用(即,字段),这样就可以使用您真正不需要的少量内存.

As a simplistic example, suppose you had some container class which wraps a T[] array, and you give this container an Empty method. It might make sense to set the container's internal array to null in this method, which would result in zero references to the array object, qualifying it for garbage collection. (You would then create a new array when external code next tried to add a T to the collection.) If you did not set the field to null on Empty, then there would still be a reference to the array (i.e., the field), and so that would be a small amount of memory being used that you really don't need.

就像我说的那样,这是一个简单的例子.老实说,您很少需要考虑这样的情况.我以为我会提到它,以免给您留下错误的印象,即将 field 设置为Nothing根本不会完成任何事情.

Like I said, that's a simplistic example. And honestly, it's rare that you ever need to consider scenarios like that. I just thought I would mention it so that you don't get the wrong impression that setting a field to Nothing literally never accomplishes anything.

*我实际上不是在这里引用任何人;这只是我听过多次的概括.

这篇关于将变量设置为"Nothing"(无).是一个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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