如果结果与if不同,为什么要内联C#? [英] Why C# inline if result is different than if?

查看:58
本文介绍了如果结果与if不同,为什么要内联C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

object w = 44;
var k1 = (w is double
       ? ((Convert.ToSingle(w)))
       : ((unchecked((uint)Convert.ToInt64(w)))));
if (w is double)
{
    w = 22;
}

结果是 k1 = 44.0和 w == 44;

The result is that k1 = 44.0 and w == 44;

我想知道为什么结果不一样!

I wonder why the results is different!

我们假设 w 是双精度的,在这种情况下, k1 应该是44.0,而 w 应该是22.

Let's assume w is double, in this case k1 should be 44.0 and w should be 22.

现在让我们假设 w 不是两倍,在这种情况下, k1 应该是44,而 w 应该是44.

Now let's assume w is not double, in this case k1 should be 44 and w should be 44.

出什么问题了??

推荐答案

无论 w 变成哪种类型,用于初始化 k1 的条件表达式的类型都是相同的出来是.编译器必须根据两个可能值的类型在编译时确定条件表达式的类型.

The type of the conditional expression used to initialize k1 is the same no matter what type w turns out to be. The compiler has to determine the conditional expression type at compile time based on the types of the 2 possible values.

cond ? float: uint

这些类型不同,但是 uint 可以隐式转换为 float ,因此编译器选择将其作为返回类型

These types are not the same but uint can implicitly convert to float hence the compiler chooses that as the return type

这篇关于如果结果与if不同,为什么要内联C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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