通常,问号主要用于条件句x ?“yes”:“no”。

但我看到过它的另一种用法,但找不到解释?例如,操作员。

public int? myProperty
{
   get;
   set;
}

当前回答

再加上其他答案:

从c# 8.0开始,Nullable<>和?并不总是可以互换的。Nullable<>仅适用于值类型,而?适用于引用类型和值类型。

这些可以在文档中看到

可空引用类型使用与nullable相同的语法进行标记 取值类型:a ?附加到变量的类型后。”

这里

<T> where T: struct

其他回答

这意味着所讨论的值类型是可空类型

Nullable types are instances of the System.Nullable struct. A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true, false, or null. The ability to assign null to numeric and Boolean types is especially useful when you are dealing with databases and other data types that contain elements that may not be assigned a value. For example, a Boolean field in a database can store the values true or false, or it may be undefined. class NullableExample { static void Main() { int? num = null; // Is the HasValue property true? if (num.HasValue) { System.Console.WriteLine("num = " + num.Value); } else { System.Console.WriteLine("num = Null"); } // y is set to zero int y = num.GetValueOrDefault(); // num.Value throws an InvalidOperationException if num.HasValue is false try { y = num.Value; } catch (System.InvalidOperationException e) { System.Console.WriteLine(e.Message); } } }

它声明该类型是可空的。

它是Nullable<int>的缩写。Nullable<T>用于允许将值类型设置为null。值类型通常不能为空。

In

x ? "yes" : "no"

的吗?声明一个if语句。这里:x表示布尔条件;在:之前的部分是then句,之后的部分是else句。

例如,

int?

的吗?声明一个可空类型,并意味着它前面的类型可能有一个空值。

实际的用法:

public string someFunctionThatMayBeCalledWithNullAndReturnsString(int? value)
{
  if (value == null)
  {
    return "bad value";
  }

  return someFunctionThatHandlesIntAndReturnsString(value);
}