在调用 C # 8.0中的方法之前,叹号是什么意思?

我发现了一个用 C # 编写的代码,看起来像是8.0版本。在代码中,在调用方法之前有一个叹号。这部分代码是什么意思,最重要的是,它的用途是什么?

var foo = Entity!.DoSomething();
56444 次浏览

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.

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

! 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 suppresses 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;