C# ? : operator

标签 c# .net operators ternary-operator

有人可以向我解释以下编译器问题

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

编译器无法确定此表达式的类型,因为 intstring 之间没有隐式转换。您已经找到了解决方案 - 调用 ToString 意味着表达式在任何一种情况下都返回一个 string。您可以修复它的另一种方法(但由于装箱,在这种情况下效率稍低)是明确告诉编译器如何执行转换。例如,您可以使用显式转换为 object:

(_Obj == null) ? "unknown" : (object)_Obj.Id

你的第二个例子没有显式转换,因为 string.Format 需要一个 object 并且有一个从 int 的隐式转换>对象

关于C# ? : operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4183959/

相关文章:

.net - 通过电子邮件将文件上传到 Windows Azure

c# - ASP.NET MVC 帮助程序扩展和关注点分离

.net - 尝试在 Azure Publish 上验证图形客户端时出现异常 : "Failed to acquire token silently. Call method AcquireToken"

c# - 如何创建类的对象,其中类名存储在 C# 中的字符串变量中

.net - 在 Azure 上运行 .NET 应用程序

gradle - Gradle 中的冒号运算符是什么?

python - 覆盖python中的所有运算符

javascript - 谷歌应用程序脚本: Illegally formed XML syntax

c# - 我应该在 Model 还是 ViewModel 上实现业务逻辑

c# - .Net 4.0 和 .NET 4.7.2 标题选择之间 DataGridView 的重大变化