在C#中处理null dereference [英] Handling null dereference in C#
本文介绍了在C#中处理null dereference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
if(conection.State!= ConnectionState.Closed){conection.Close(); }
我尝试了什么:
以上代码的作用没有Null Dereference?请建议
解决方案
没什么。如果connection
为null,它仍会抛出异常。
试试这个:
if(connection!= null&& conection.State!= ConnectionState.Closed)
{
conection.Close();
}但更好的是,在创建连接时使用
使用
块,以便在超出范围时自动关闭并处理。
if (conection.State != ConnectionState.Closed) { conection.Close(); }
What I have tried:
What makes the above code free from Null Dereference? Kindly suggest
解决方案
Nothing. Ifconnection
is null, it will still throw an exception.
Try this:
if (connection != null && conection.State != ConnectionState.Closed) { conection.Close(); }But better, use a
using
block around your connection creation so it is automatically closed and disposed when it goes out of scope.
这篇关于在C#中处理null dereference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文