How to avoid a NullReferenceException

末鹿安然 提交于 2019-12-08 05:52:29

问题


 if (alMethSign[z].ToString().Contains(aClass.Namespace))

Here, I load an exe or dll and check its namespace. In some dlls, there is no namespace, so aclass.namespace is not present and it's throwing a NullReferenceException.

I have to just avoid it and it should continue with rest of the code. If I use try-catch, it executes the catch part; I want it to continue with the rest of the code.


回答1:


Is aClass a Type instance? If so - just check it for null:

if (aClass != null && alMethSign[z].ToString().Contains(aClass.Namespace))



回答2:


Don't catch the exception. Instead, defend against it:

string nmspace = aClass.Namespace;

if (nmspace != null && alMethSign[z].ToString().Contains(nmspace))
{
    ...
}



回答3:


Add the test for null in the if statement.

if(aClass.NameSpace != null && alMethSign[z].ToString().Contains(aClass.Namespace))



回答4:


Or use an extension method to that checks for any nulls and either returns an empty string or the string value of the object:

public static string ToSafeString(this object o)
{
return o == null ? string.Empty : o.ToString();

}


来源:https://stackoverflow.com/questions/733383/how-to-avoid-a-nullreferenceexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!