ser*_*hio 4 .net c# operators ternary-operator
有人可以解释一下以下编译器问题
错误:无法确定条件表达式的类型,因为'string'和'int'之间没有隐式转换
// WORKS
string text = string.Format(
"the id is {0}", _Obj.Id.ToString());
// WORKS, without implicit conversion <<<
string text = string.Format(
"the id is {0}", _Obj.Id);
// WORKS
string text = string.Format(
"the id is {0}", (_Obj == null) ? "unknown" : _Obj.Id.ToString());
// NO WAY <<<
string text = string.Format(
"the id is {0}", (_Obj == null) ? "unknown" : _Obj.Id);
Run Code Online (Sandbox Code Playgroud)
在最后一个示例中,也没有隐式转换.
Mar*_*ers 10
问题与您的使用无关string.Format.问题是这个表达式:
(_Obj == null) ? "unknown" : _Obj.Id
Run Code Online (Sandbox Code Playgroud)
编译器无法确定此表达式的类型,因为int和之间没有隐式转换string.您已经找到了解决方案 - 调用ToString意味着表达式string在任何一种情况下都返回a .你可以修复它的另一种方法(但由于装箱而在这种情况下效率略低)是告诉编译器明确如何执行转换.例如,您可以使用显式强制转换object:
(_Obj == null) ? "unknown" : (object)_Obj.Id
Run Code Online (Sandbox Code Playgroud)
你的第二个例子工程没有进行明确的转换,因为string.Format期望的object并且有一个隐式转换从int到object.