使用条件运算符时的评估顺序

HAB*_*JAN 0 c#

是否有以下行为?

public class TestClass
{
    public int IntValue { get; set; }
}

TestClass instance = null;

// this line throws exception: Object reference not set to an instance of an object 
string test1 = "abc" + instance != null ? instance.IntValue.ToString() : "0";

// this works
string test2 = instance != null ? instance.IntValue.ToString() : "0";

// this works
string test3 = "abc" + (instance != null ? instance.IntValue.ToString() : "0");
Run Code Online (Sandbox Code Playgroud)

更新:

为什么这不会抛出异常?

TestClass instance = null;
string test4 = "abc" + instance;
string test5 = "abc" + true;
Run Code Online (Sandbox Code Playgroud)

Sef*_*efe 10

您的问题是运营商优先级.+排名高于!= ?:.你的行无效也可以写成:

string test1 = ("abc" + instance) != null ? instance.IntValue.ToString() : "0";
Run Code Online (Sandbox Code Playgroud)

表达"abc" + instance从来没有 null,即使instancenull.这意味着你的表达式总是计算为true,这使得你NullReferenceExceptioninstance.IntValue.ToString()表达式中遇到的情况instancenull.

您可以使用parenthisation覆盖运算符优先级.这意味着您必须instance != null ? instance.IntValue.ToString()首先通过将其括在括号中来确保首先进行评估:

string test1 = "abc" + (instance != null ? instance.IntValue.ToString() : "0");
Run Code Online (Sandbox Code Playgroud)

更新:

就更新中的问题而言:这些表达式不会引发错误,因为关于+字符串上的运算符实现有两个细节:

  1. null只要您在另一侧有一个有效的字符串,它就可以容忍值.
  2. 由于该ToString方法实现System.Object,任何值都可以转换为字符串ToString.因此,可以将非字符串值添加到字符串(仅在右侧).