首先,我想我知道发生了什么,但我想我会把这个问题带到这里进行一些讨论,看看是否有人对这个问题有"回答",而不是我在想什么.因为,这对我来说并不完全有意义.
我发现在为异常创建错误日志时,我这样做并且它无法正常工作:
catch( Exception ex )
{
LogException( ex.Message );
if ( !string.IsNullOrEmpty( ex.InnerException.Message ) )
{
LogInnerException( ex.InnerException.Message );
}
}
Run Code Online (Sandbox Code Playgroud)
瞧,当我跑这个时,我经常得到一个NullReferenceException.咦?
我正在检查null,对吗?
现在,我必须使用这个:
if ( ex.InnerException != null && !string.IsNullOrEmpty( ex.InnerException.Message )
Run Code Online (Sandbox Code Playgroud)
但这似乎是违反直觉的,也会产生反作用.因为,如果我这样做:
if ( !string.IsNullOrEmpty( null ) )
Run Code Online (Sandbox Code Playgroud)
这根本不会给我任何问题.如果ex.InnerException为null,那么当然ex.InnerException.Message为null,对吗?
显然不是.
我写了一个完整的控制台应用程序来重现这个.如果你
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace stringisnullorempty
{
class Program
{
static void Main( string[] args )
{
if ( !string.IsNullOrEmpty( null ) )
{
Console.WriteLine( "Ha ha ha, right...." );
}
MyBClass …Run Code Online (Sandbox Code Playgroud)