What does exclamation mark mean before invoking a method in C# 8.0? [duplicate]

冷暖自知 提交于 2020-04-05 12:40:57

问题


I have found a code written in C# seemingly version 8.0. In the code, there is an exclamation mark before invoking a method. What does this part of the code mean, and above all, what are its uses?

var foo = Entity!.DoSomething();

回答1:


This would be the null forgiving operator.
It tells the compiler "this isn't null, trust me", so it does not issue a warning for a possible null reference.

In this particular case it tells the compiler that Entity isn't null.




回答2:


! is the Null-Forgiving Operator. To be specific it has two main effects:

  • it changes the type of the expression (in this case it modifies Entity) from a nullable type into a non-nullable type; (for example, object? becomes object)

  • it supresses nullability related warnings, which can hide other conversions

This seems to come up particularly with type parameters:

IEnumerable<object?>? maybeListOfMaybeItems = new object[] { 1, 2, 3 };

// inferred as IEnumerable<object?>
var listOfMaybeItems = maybeListOfMaybeItems!;

// no warning given, because ! supresses nullability warnings
IEnumerable<object> listOfItems = maybeListOfMaybeItems!;

// warning about the generic type change, since this line does not have !
IEnumerable<object> listOfItems2 = listOfMaybeItems;



回答3:


This is called the null-forgiving operator and is available in C# 8.0 and later. It has no effect at run time, only at compile time. It's purpose is to inform the compiler that some expression of a nullable type isn't null to avoid possible warnings about null references.

In this case it tells the compiler that Entity isn't null.




回答4:


It means non-nullable.

For example:

int can not be null by its nature but we can declare nullable int like:

Nullable<int> x;

or

int? x;

However, some classes can be null even if we don't say so.

for example

string x = null;

and we don't need to declare it as:

string? x;

To make sure that declared variable cannot be null (non-nullable), ! is used, so:

string! x = "somevalue";

it means that x can not accept null as a value.

https://docs.microsoft.com/en-us/archive/msdn-magazine/2018/february/essential-net-csharp-8-0-and-nullable-reference-types



来源:https://stackoverflow.com/questions/59230542/what-does-exclamation-mark-mean-before-invoking-a-method-in-c-sharp-8-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!