有没有什么好的理由在C#ternaries是有限的? [英] Are there any good reasons why ternaries in C# are limited?

查看:119
本文介绍了有没有什么好的理由在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是有限的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆