后缀!C#中的(感叹号)运算符 [英] Postfix ! (exclamation) operator in C#

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

问题描述

最后一天,我在GitHub上探索.NET源代码,偶然发现了以下结构:(((SomeTypeToCast)variable!).SomeMethodToCall().

The last day I was exploring .NET sources on GitHub and stumbled upon the following construct: ((SomeTypeToCast)variable!).SomeMethodToCall().

请注意后缀 ,该后缀最初是那么,一个简单的问题:这是什么?

So, the simple question: what's this?

P.S .:就我个人而言,我对这个东西可能意味着几个猜测:有点这个值永远不会为空".但是,在C#中没有这样的运算符(至少是公开可用的),当我自己在测试项目中尝试使用该表达式时,该表达式将无法编译.

P.S.: Personally I've got a couple surmises on what this thing may mean: kind of "this value is never null". However there is no such operator in C# (at least publicly available) and such expression fails to compile when I'm trying it in test project myself.

推荐答案

这是C#8中的 null-forgiving 运算符(也称为"damn-it"运算符),可以有效地告诉编译器假定该值将为非null.在告诉编译器您比它更了解方面,它有点像转换(cast),但是在执行时它没有效果,所以您实际上绕过了编译器检查的安全性.

This is the null-forgiving operator (also known as the "damn-it" operator) in C# 8, which effectively tells the compiler to assume that the value will be non-null. It's a little like a cast, in terms of telling the compiler that you know better than it does - but it has no effect at execution time, so you're effectively bypassing the safety of the compiler checks.

它是 C#8可为空引用类型功能. 在.NET Core 3.0 SDK的公共预览版本中可用.

It's introduced as part of the C# 8 nullable-reference type feature. It is available in public preview builds of .NET Core 3.0 SDK.

我的经验中的典型用法:

Typical uses in my experience:

  • 测试参数验证代码,以证明如果 do 将null传递给方法,则必须进行验证才能抛出 ArgumentNullException
  • 可以确定该值不会为null的地方,这是由于编译器不知道的其他不变量所致.(例如,在Noda Time中,我有一个 ParseResult< T> ,其中包含一个值字段和一个异常提供程序.异常提供程序为null或值为null,但都不是两者,而我使用该值之前,请务必先检查异常提供程序.)
  • Testing your argument validation code, to prove that if you do pass null into a method, you've got validation to throw ArgumentNullException
  • Places where you're certain the value won't be null due to other invariants that the compiler isn't aware of. (For example, in Noda Time I have a ParseResult<T> which has fields of a value and an exception provider. Either the exception provider is null or the value is null, but never both, and I always check the exception provider before using the value.)

这篇关于后缀!C#中的(感叹号)运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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