What does the bool? return type mean?

后端 未结 3 770
猫巷女王i
猫巷女王i 2020-12-06 11:44

I saw a method return bool?, does anyone know the meaning of it?

3条回答
  •  情话喂你
    2020-12-06 12:08

    T? is a C# syntax shortcut to Nullable. So bool? maps to Nullable. So in your case it's a struct that either is null, or has a bool value.

    If a Nullable is null that's a bit different from a reference type being null. It basically is a struct containing the underlying type and a boolean flag HasValue. But both the runtime and the C# language have a bit of magic to pretend that a Nullable with HasValue==false is really null. But the difference still leaks sometimes.

    The underlying type is implicitly convertible to the nullable type (bool->bool?). To get the underlying type from the nullable type, you can either cast explicitly ((bool)myNullableBool or use the Value property (myNullableBool.Value). You should check for null before though, or you'll get an exception if the nullable value is null.

    • Nullable Types (C# Programming Guide)
    • Nullable

提交回复
热议问题