声明整数为空

Declare integer as null

一般我们这样声明变量属性:

int a = 0;

我想将一个 整数声明为 null。我该怎么做?

我的预期输出是

int i = null;

您可以使用 Nullable<T> 类型:

int? i = null;

C# Data types are divided into value types and reference type. By default value types are not nullable. But for reference type is null.

string name = null;
Int ? i = null; // declaring nullable type

如果要将值类型设置为可为空,请使用 ?

Int j = i;  //this will through the error because implicit conversion of nullable 
            // to non nullable is not possible `

使用

int j =i.value;

int j =(int) i;

C# 中的值类型不可为空,除非您明确定义它们。如果你想允许 int 为 null,你必须像这样声明你的变量:

int? i = null;

整数是一种值类型,其初始化时的默认值为0。

https://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

你不能让它为空,编译器不会让你使用未初始化的整数。

如果您需要将 null 分配给一个整数,无论​​出于何种原因,您都应该使用 Nullable 引用类型。诠释? = 空。希望对您有所帮助。