gpt4 book ai didi

c# - C# 中的三元组受到限制有什么充分的理由吗?

转载 作者:太空狗 更新时间:2023-10-29 17:28:39 26 4
gpt4 key购买 nike

失败:

object o = ((1==2) ? 1 : "test");

成功:

object o;
if (1 == 2)
{
o = 1;
}
else
{
o = "test";
}

第一条语句的错误是:

Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and 'string'.

为什么需要这样,我将这些值分配给对象类型的变量。

编辑:上面的例子是微不足道的,是的,但有些例子会很有帮助:

int? subscriptionID; // comes in as a parameter

EntityParameter p1 = new EntityParameter("SubscriptionID", DbType.Int32)
{
Value = ((subscriptionID == null) ? DBNull.Value : subscriptionID),
}

最佳答案

使用:

object o = ((1==2) ? (object)1 : "test");

问题在于无法明确确定条件运算符的返回类型。也就是说,在int和string之间,没有最好的选择。编译器将始终使用 true 表达式的类型,并在必要时隐式转换 false 表达式。

编辑:在你的第二个例子中:

int? subscriptionID; // comes in as a parameter

EntityParameter p1 = new EntityParameter("SubscriptionID", DbType.Int32)
{
Value = subscriptionID.HasValue ? (object)subscriptionID : DBNull.Value,
}

附言:
那不叫“三元运算符”。它一个三元运算符,但它被称为“条件运算符”。

关于c# - C# 中的三元组受到限制有什么充分的理由吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1669492/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com