检查对象创建后空

检查对象创建后空

本文介绍了检查对象创建后空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个新的对象

myobject t = new myobject();

我应该检查下一行的空引用,如果新的成功?

should I check on the next line for null reference , if the new succeeded ?

if (null != t)

或者我可以肯定,这个对象肯定会不同,那么空...

or I can be sure that this object for sure will be different then null ...

感谢。

推荐答案

据的,如果未能成功分配空间用于新的对象实例,一个 OutOfMemoryException异常将被抛出。因此,有没有必要做一个明确的检查

According to the C# documentation, if new fails to successfully allocate space for a new object instance, an OutOfMemoryException will be thrown. So there's no need to do an explicit check for null.

如果你想检测的情况下,其中未能分配一个新的对象,你可能想要做的是这样的:

If you are trying to detect cases where new has failed to allocate a new object, you might want to do something like:

try {
    myobject t = new myobject();
    //do stuff with 't'
}
catch (OutOfMemoryException e) {
    //handle the error (careful, you've run out of heap space!)
}

这篇关于检查对象创建后空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:16