我有以下代码:
public void DrawInput(string ChatCurrent){
int uCursorTop;
int uCursorLeft;
uCursorLeft = Console.CursorLeft;
uCursorTop = Console.CursorTop;
Console.SetCursorPosition(0, uCursorTop);
Console.Write("> "+ChatCurrent+" ");
Console.SetCursorPosition(ChatCurrent.Length, uCursorTop);
}
Run Code Online (Sandbox Code Playgroud)
除了最后一行,它表现得很好.最后一行抛出System.NullReferenceException: Object reference not set to an instance of an object.奇怪的是?具体来说,访问ChatCurrent.Length是使它失败的原因.紧接着之前的那一行,它回应了字符串的内容,效果很好.
这是怎么回事?
字符串连接将null值视为空字符串
在字符串连接操作中,C#编译器将空字符串视为空字符串,但它不会转换原始空字符串的值.
http://msdn.microsoft.com/en-us/library/ms228504.aspx
但即使你null直接传递给Console.Write它,它也不会抛出异常,它只会写不出来.
http://msdn.microsoft.com/en-us/library/zcwe8sfx%28v=vs.80%29.aspx
如果value是空引用(在Visual Basic中为Nothing),则不会写入任何内容,也不会引发异常.