有没有什么好的理由在C#ternaries是有限的?

编程入门 行业动态 更新时间:2024-10-14 14:19:40
本文介绍了有没有什么好的理由在C#ternaries是有限的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

失败:

对象o =((1 == 2)?1:测试);

成功:

对象o; 如果(1 == 2) { O = 1; } ,否则 { O =测试; }

在第一条语句的错误是:

无法确定条件表达式的类型,因为有'廉政'和'串'之间不存在隐式转换。

为什么我们需要有不过,我这些值分配给对象类型的变量

修改: 上面的例子是微不足道的,肯定的,但也有例子,这将是非常有帮助的:

诠释? subscriptionID; //进来作为一个参数 EntityParameter P1 =新EntityParameter(SubscriptionID,DbType.Int32) {值=((subscriptionID == NULL)?为DBNull。价值:subscriptionID),}

解决方案

使用

对象o =((1 == 2)(目标)?1:测试);

的问题是,条件运算符的返回类型不能为未含糊决心。也就是说,int和string之间,没有最好的选择。该编译器将始终使用真实表达的类型,并在必要时隐式转换虚假的表达

编辑: 在你第二个例子:

诠释? subscriptionID; //进来作为一个参数 EntityParameter P1 =新EntityParameter(SubscriptionID,DbType.Int32) {值= subscriptionID.HasValue? (对象)subscriptionID:DBNull.Value,}

PS: 那不叫三元运算符。它的是的三元运算符,但它被称为有条件的经营者。

Fails:

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

Succeeds:

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

The error in the first statement is:

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

Why does there need to be though, I'm assigning those values to a variable of type object.

Edit: The example above is trivial, yes, but there are examples where this would be quite helpful:

int? subscriptionID; // comes in as a parameter EntityParameter p1 = new EntityParameter("SubscriptionID", DbType.Int32) { Value = ((subscriptionID == null) ? DBNull.Value : subscriptionID), }

解决方案

use:

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

The issue is that the return type of the conditional operator cannot be un-ambiguously determined. That is to say, between int and string, there is no best choice. The compiler will always use the type of the true expression, and implicitly cast the false expression if necessary.

Edit: In you second example:

int? subscriptionID; // comes in as a parameter EntityParameter p1 = new EntityParameter("SubscriptionID", DbType.Int32) { Value = subscriptionID.HasValue ? (object)subscriptionID : DBNull.Value, }

PS: That is not called the 'ternary operator.' It is a ternary operator, but it is called the 'conditional operator.'

更多推荐

有没有什么好的理由在C#ternaries是有限的?

本文发布于:2023-11-22 01:05:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615368.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有没有什么   理由   ternaries

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!