为什么不能使用'as'运算符来解析不可为空的值类型? [英] Why can the 'as' operator not be used to parse non-nullable value types?

查看:42
本文介绍了为什么不能使用'as'运算符来解析不可为空的值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个开发人员都有自己的标准.一些开发人员喜欢< type> .TryParse(),一些开发人员喜欢使用(type)object; 进行转换,而一些开发人员则喜欢使用关键字来代替.

Every Developer has his/her own standards. Some developers like to <type>.TryParse(), some developers like to cast using (type)object;, and some developers love using the keywords instead.

我注意到'as'运算符引起了麻烦-您不能使用它在非空值类型之间执行转换.我在MSDN上的as关键字上阅读了文档,他们也将其解释为您可以使用as运算符在兼容的引用类型或可为空的类型之间执行某些类型的转换."

I noticed a hiccup with the 'as' operator - you cannot use it to perform conversions between non-nullable value types. I read the documentation on MSDN on the as Keyword and they also explain it as "You can use the as operator to perform certain types of conversions between compatible reference types or nullable types."

我用以下方法对此进行了测试:

I tested this with the following:

                    int i = 0;
                    var k = i as int; //Breaks

                    int i = 0;
                    var k = i as int?; //Works

决定 as 关键字以这种方式执行的原因是什么?

What were the reasons decided for the as keyword to perform in this way?

推荐答案

as 运算符将在解析失败时返回 null .由于 int 是不可为空的值类型,因此会出现错误,而 int? Nullable< int> 可以容纳 null 值,这就是第二个代码段起作用的原因.

as operator would return null if parsing fails. Since int is a non nullable value type, you get the error, whereas int? or Nullable<int> can hold null value, that is why your second code snippet works.

请参阅:作为(C#参考)

您可以使用as运算符执行某些类型的转换兼容的引用类型或可为空的类型

也来自同一文档链接

as运算符就像强制转换操作一样.但是,如果转换不可能,因为返回null而不是引发异常.

这篇关于为什么不能使用'as'运算符来解析不可为空的值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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