是否有以下行为?
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,即使instance是null.这意味着你的表达式总是计算为true,这使得你NullReferenceException在instance.IntValue.ToString()表达式中遇到的情况instance是null.
您可以使用parenthisation覆盖运算符优先级.这意味着您必须instance != null ? instance.IntValue.ToString()首先通过将其括在括号中来确保首先进行评估:
string test1 = "abc" + (instance != null ? instance.IntValue.ToString() : "0");
Run Code Online (Sandbox Code Playgroud)
更新:
就更新中的问题而言:这些表达式不会引发错误,因为关于+字符串上的运算符实现有两个细节:
null只要您在另一侧有一个有效的字符串,它就可以容忍值.ToString方法实现System.Object,任何值都可以转换为字符串ToString.因此,可以将非字符串值添加到字符串(仅在右侧).| 归档时间: |
|
| 查看次数: |
312 次 |
| 最近记录: |