有人可以向我解释以下编译器问题
Error: Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and '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);
在最后一个例子中,也没有隐式转换。
最佳答案
问题与您对 string.Format
的使用无关。问题是这个表达式:
(_Obj == null) ? "unknown" : _Obj.Id
编译器无法确定此表达式的类型,因为 int
和 string
之间没有隐式转换。您已经找到了解决方案 - 调用 ToString
意味着表达式在任何一种情况下都返回一个 string
。您可以修复它的另一种方法(但由于装箱,在这种情况下效率稍低)是明确告诉编译器如何执行转换。例如,您可以使用显式转换为 object
:
(_Obj == null) ? "unknown" : (object)_Obj.Id
你的第二个例子没有显式转换,因为 string.Format
需要一个 object
并且有一个从 int
到 的隐式转换>对象
。
关于C# ? : operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4183959/