C#中的三元数据有什么好的原因吗?

前端之家收集整理的这篇文章主要介绍了C#中的三元数据有什么好的原因吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
失败:
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,}

PS:这不是所谓的“三元运算符”.它是一个三元运算符,但它被称为“条件运算符”.

原文链接:https://www.f2er.com/csharp/96186.html

猜你在找的C#相关文章