为什么编译器不能自动正确地转换这个表达式中的值?
var input = "Hello";
object x = string.IsNullOrEmpty(input) ? input : DBNull.Value;
//could try this too and get similar compile time error
object x2 = string.IsNullOrEmpty(input) ? 1 : input;
我知道 DBNull.Value 不能转换为字符串;但是,我很好奇为什么它不能合并到一个对象中,因为结果只是存储一个引用。如果将 (object)
放在 DBNull.Value 前面,它将编译并运行得很好。
最佳答案
这是因为 string
不能转换为 DbNull
,反之亦然。使用三元运算符时,两个结果操作数必须兼容。
关于C# 三元表达式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10590923/