問題描述
如果對象為空,我想阻止對其進(jìn)行進(jìn)一步處理.
在下面的代碼中,我檢查對象是否為空:
if (!data.Equals(null))
和
if (data != null)
但是,我在 dataList.Add(data)
收到一個(gè) NullReferenceException
.如果對象為空,它甚至不應(yīng)該進(jìn)入 if
語句!
因此,我在問這是否是檢查對象是否為空的正確方法:
public List
如果這是檢查對象是否為空的正確方法,我做錯(cuò)了什么(如何防止對對象進(jìn)行進(jìn)一步處理以避免 NullReferenceException)?
null
不是data
,而是dataList
.>
您需要?jiǎng)?chuàng)建一個(gè)
public List
更好:因?yàn)樗且粋€(gè)字段,所以將其設(shè)為私有
.如果沒有什么可以阻止您,請將其設(shè)置為 readonly
.只是很好的做法.
旁邊
檢查無效性的正確方法是if(data != null)
.這種檢查在引用類型中無處不在;甚至 Nullable<T>
覆蓋了相等運(yùn)算符,以便在檢查 null 性時(shí)更方便地表達(dá) nullable.HasValue
.
如果你執(zhí)行 if(!data.Equals(null))
那么你會(huì)得到一個(gè) NullReferenceException
如果 data == null
.這有點(diǎn)可笑,因?yàn)楸苊膺@種例外是首要目標(biāo).
你也在這樣做:
catch(異常 e){拋出新的異常(e.ToString());}
這絕對不好.我可以想象你把它放在那里只是為了你可以在方法內(nèi)部時(shí)進(jìn)入調(diào)試器,在這種情況下忽略這一段.否則,不要無緣無故地捕獲異常.如果你這樣做了,只需使用 throw;
重新拋出它們.
I would like to prevent further processing on an object if it is null.
In the following code I check if the object is null by either:
if (!data.Equals(null))
and
if (data != null)
However, I receive a NullReferenceException
at dataList.Add(data)
. If the object was null, it should never have even entered the if
-statement!
Thus, I'm asking if this is proper way of checking if an object is null:
public List<Object> dataList;
public bool AddData(ref Object data)
bool success = false;
try
{
// I've also used "if (data != null)" which hasn't worked either
if (!data.Equals(null))
{
//NullReferenceException occurs here ...
dataList.Add(data);
success = doOtherStuff(data);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return success;
}
If this is the proper way of checking if the object is null, what am I doing wrong (how can I prevent further processing on the object to avoid the NullReferenceException)?
It's not data
that is null
, but dataList
.
You need to create one with
public List<Object> dataList = new List<Object>();
Even better: since it's a field, make it private
. And if there's nothing preventing you, make it also readonly
. Just good practice.
Aside
The correct way to check for nullity is if(data != null)
. This kind of check is ubiquitous for reference types; even Nullable<T>
overrides the equality operator to be a more convenient way of expressing nullable.HasValue
when checking for nullity.
If you do if(!data.Equals(null))
then you will get a NullReferenceException
if data == null
. Which is kind of comical since avoiding this exception was the goal in the first place.
You are also doing this:
catch (Exception e)
{
throw new Exception(e.ToString());
}
This is definitely not good. I can imagine that you put it there just so you can break into the debugger while still inside the method, in which case ignore this paragraph. Otherwise, don't catch exceptions for nothing. And if you do, rethrow them using just throw;
.
這篇關(guān)于在 C# 中檢查對象是否為空的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!