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

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

public int? myProperty
{
   get;
   set;
}

它声明该类型是可空的。


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


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

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); } } }


In

x ? "yes" : "no"

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

例如,

int?

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


实际的用法:

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

  return someFunctionThatHandlesIntAndReturnsString(value);
}

为了补充上面的答案,这里有一个代码示例

struct Test
{
    int something;
}
struct NullableTest
{
    int something;
}
class Example
{
    public void Demo()
    {
        Test t = new Test();
        t = null;

        NullableTest? t2 = new NullableTest();
        t2 = null;
    }
}

这将给出一个编译错误:

错误12不能将null转换为“Test”,因为它是非空的 值类型

注意NullableTest没有编译错误。(注意?在t2的声明中)


int ?是Nullable<int>的缩写。这两种形式是可以互换的。

Nullable<T>是一个操作符,可以与值类型T一起使用,使其接受空值。

以防你不知道:值类型是接受int, bool, char等值的类型……

它们不能接受对值的引用:如果给它们分配一个空值,它们会生成一个编译时错误,而引用类型显然可以接受空值。

你为什么需要这个? 因为有时候你的值类型变量可能会收到一些工作不太好的东西返回的空引用,比如从数据库返回的一个缺失的或未定义的变量。

我建议你阅读微软文档,因为它很好地涵盖了这个主题。


表示用(int?)声明的变量是可空的

int i1=1; //ok
int i2=null; //not ok

int? i3=1; //ok
int? i4=null; //ok

再加上其他答案:

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

这些可以在文档中看到

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

这里

<T> where T: struct