C# 转换为可空类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10065452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# casting to nullable type?
提问by Royi Namir
Beyondthe regular boring difference between Castand As
超越Cast和之间的常规无聊差异As
- if i knowthat appleis a Fruitso I can use
(Fruit)apple- and it throws an exception if it aint as valuecan be checked against null to see if succeeded [won't throw Exception...]
- 如果我知道那个苹果是水果,所以我可以使用
(Fruit)apple-如果它是不是它抛出一个异常 as value可以检查 null 以查看是否成功[不会抛出异常...]
However Ive been reading @EricLippert articleabout this and there was a nice sample about Nullable Value Types :
但是,我一直在阅读有关此内容的 @EricLippert文章,并且有一个关于 Nullable Value Types 的不错示例:
short? s = (short?)123;
int? i = s as int?;
this won'tcompile...
这不会编译...
Cannot convert type 'short?' to 'int?' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
无法转换类型“短?” 'int?通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换
Fine.
美好的。
so why this :
那么为什么这样:
short? s = (short?)123;
int? i = (int?)s;
DoesCompile ? ( Against ALL Expectations! I KNOWthat sis not int?- and it should go BANG but it aint ...)
是否编译?(出乎所有人的意料!我知道这s不是 int?- 它应该爆炸,但它不是......)
the Cast checking here should be much more deadly than the former example (which went Bang)
这里的演员检查应该比前一个例子(爆炸)更致命
I feel bad asking about this much-talked subject.
问到这个热门话题,我感到很不好意思。
Thanks in Advance.
提前致谢。
采纳答案by sblom
In your first example, the asoperator attempts to use the object sas an int?. Since int?isn't anywhere in the inheritance chain of short?, this operation fails.
在您的第一个示例中,as运算符尝试将该对象s用作int?. 由于int?不在 的继承链中short?,因此此操作失败。
In your second example, you're actually creating a new int? iwith the value from short? s. This is a more generous operation, because it doesn't have to preserve the original sobject on the left hand side.
在您的第二个示例中,您实际上是在创建一个int? i值为 from的 new short? s。这是一个更慷慨的操作,因为它不必保留s左侧的原始对象。
The important point here is that asisn't allowed to do anything that doesn't preserve your object's identity. An explicit cast can.
这里的重点是as不允许做任何不保留对象身份的事情。显式强制转换可以。
Here's what the C# standard says about how the (int?)form works:
以下是 C# 标准关于(int?)表单如何工作的说明:
6.1.4 Implicit nullable conversions
Predefined implicit conversions that operate on non-nullable value types can also be used with nullable forms of those types. For each of the predefined implicit identity and numeric conversions that convert from a non-nullable value type S to a non-nullable value type T, the following implicit nullable conversions exist:
· An implicit conversion from S? to T?.
· An implicit conversion from S to T?.
Evaluation of an implicit nullable conversion based on an underlying conversion from S to T proceeds as follows:
· If the nullable conversion is from S? to T?:
o If the source value is null (HasValue property is false), the result is the null value of type T?.
o Otherwise, the conversion is evaluated as an unwrapping from S? to S, followed by the underlying conversion from S to T, followed by a wrapping (§4.1.10) from T to T?.
· If the nullable conversion is from S to T?, the conversion is evaluated as the underlying conversion from S to T followed by a wrapping from T to T?.
6.1.4 隐式可空转换
对不可为空的值类型进行操作的预定义隐式转换也可以与这些类型的可空形式一起使用。对于从不可为空的值类型 S 转换为不可为空的值类型 T 的每个预定义的隐式标识和数值转换,存在以下隐式可空转换:
· 从 S 的隐式转换?到T?。
· 从 S 到 T? 的隐式转换。
基于从 S 到 T 的基础转换对隐式可为空转换的评估如下进行:
· 如果可空转换来自 S?到T?:
o 如果源值为空(HasValue 属性为假),则结果为 T? 类型的空值。
o 否则,转换被评估为从 S? 到 S,然后是从 S 到 T 的底层转换,然后是从 T 到 T? 的包装(第 4.1.10 节)。
· 如果可空转换是从 S 到 T?,则该转换被评估为从 S 到 T 的基础转换,然后是从 T 到 T? 的换行。
回答by Oded
The example:
这个例子:
int? i = (int?)s;
Does compiler because a cast is you telling the compiler that you know something that it can't infer, that is, that scan be converted to a int?.
编译器是否因为强制转换是你告诉编译器你知道一些它无法推断的东西,也就是说,s可以转换为int?.
You will only get the exception at runtime if the cast is not successful.
如果转换不成功,您只会在运行时收到异常。
回答by Tigran
I think it's cause in case of asfailure you will be given a "valid" nullresult, so false positive. In second case, cast is allowed cause in case of failure it will raise an exception.
我认为这是as失败的原因,你会得到一个“有效”的null结果,所以误报。在第二种情况下,强制转换是允许的,因为在失败的情况下它会引发异常。
回答by Andy
The reason is that int? is just shorthand for System.Nullable<int>(System.Nullable<T>is the type). The short type defines an explicit cast to an int, however System.Nullable<T>doesn't have any such explicit cast, because T could be any other value type.
原因是那个int?只是System.Nullable<int>(System.Nullable<T>是类型) 的简写。short 类型定义了对 int 的显式转换,但是System.Nullable<T>没有任何这种显式转换,因为 T 可以是任何其他值类型。

