C#:条件运算符 [英] C# ?: Conditional Operator

查看:206
本文介绍了C#:条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种提取物的C#2.0源$ C ​​$ C

I have this extract of C# 2.0 source code

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

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

而第二个没有第一个结果评价抛出一个无效的转换异常。 这两者之间的区别是什么?

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

推荐答案

更​​新:这个问题问得<一个href="http://blogs.msdn.com/b/ericlippert/archive/2010/05/27/cast-operators-do-not-obey-the-distributive-law.aspx"相对=nofollow>我的博客上2010年5月27日的主题。感谢伟大的问题!

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

有许许多多非常混乱这里的答案。让我尝试到precisely回答你的问题。让我们简化了下来:

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);

编译器如何跨preT的最后一行?面临的编译器的问题是,在类型的有条件前pression必须为两个分支一致;语言规则不允许你返回对象的一个​​分支和int为另一方。选项​​包括对象和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);

因此​​返回零是装箱的int。

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:

重新presentation和身份

基本上,你的问题是,你表现得好像要转换成十进制的发行,是这样的:

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".

这篇关于C#:条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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