使用条件/三元(“?:")运算符进行转换 [英] Casting with conditional/ternary ("?:") operator

查看:84
本文介绍了使用条件/三元(“?:")运算符进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有C#源代码的摘录:

I have this extract of C# source code:

object valueFromDatabase;
decimal result;
valueFromDatabase = DBNull.Value;

result = (decimal)(valueFromDatabase != DBNull.Value ? valueFromDatabase : 0);
result = (valueFromDatabase != DBNull.Value ? (decimal)valueFromDatabase : (decimal)0);

第一个结果评估抛出一个 InvalidCastException ,而第二个则没有.两者有什么区别?

The first result evaluation throws an InvalidCastException whereas the second one does not. What is the difference between these two?

推荐答案

更新:此问题为

UPDATE: This question was the subject of my blog on May 27th 2010. Thanks for the great question!

这里有很多非常令人困惑的答案.让我试着准确回答您的问题.让我们简化一下:

There are a great many very confusing answers here. Let me try to precisely answer your question. Let's simplify this down:

object value = whatever;
bool condition = something;
decimal result = (decimal)(condition ? value : 0);

编译器如何解释最后一行?编译器面临的问题是,条件表达式的类型对于两个分支必须是一致的;语言规则不允许您在一个分支上返回对象,而在另一分支上返回int.选择是对象和整数.每个int都可以转换为对象,但并非每个对象都可以转换为int,因此编译器选择对象.因此,这与

How does the compiler interpret the last line? The problem faced by the compiler is that the type of the conditional expression must be consistent for both branches; the language rules do not allow you to return object on one branch and int on the other. The choices are object and int. Every int is convertible to object but not every object is convertible to int, so the compiler chooses object. Therefore this is the same as

decimal result = (decimal)(condition ? (object)value : (object)0);

因此返回的零是一个装箱的整数.

Therefore the zero returned is a boxed int.

然后将int拆箱为小数.将装箱的int拆成小数是非法的.出于这个原因,请参阅我关于该主题的博客文章:

You then unbox the int to decimal. It is illegal to unbox a boxed int to decimal. For the reasons why, see my blog article on that subject:

表示与身份

基本上,您的问题是您的行为就像是对十进制进行了强制转换一样,

Basically, your problem is that you're acting as though the cast to decimal were distributed, like this:

decimal result = condition ? (decimal)value : (decimal)0;

但是正如我们所见,那不是

But as we've seen, that is not what

decimal result = (decimal)(condition ? value : 0);

表示.这意味着将两种选择都变成对象,然后将结果对象拆箱".

means. That means "make both alternatives into objects and then unbox the resulting object".

这篇关于使用条件/三元(“?:")运算符进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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