[英]Declare integer as null
Generally, we delare variable property like this: 通常,我们像这样对变量属性进行delare:
int a = 0;
I want to declare one integer as null . 我想将一个整数声明为null 。 how can I do that?
我怎样才能做到这一点?
my expected output is 我的预期输出是
int i = null;
您可以使用Nullable<T>
类型:
int? i = null;
C# Data types are divided into value types and reference type.
C#数据类型分为值类型和引用类型。 By default value types are not nullable.
默认情况下,值类型不能为空。 But for reference type is null.
但对于引用类型,则为null。
string name = null;
Int ? i = null; // declaring nullable type
If you want to make value type as nullable use ?
如果要使值类型可为空,请使用
?
Int j = i; //this will through the error because implicit conversion of nullable
// to non nullable is not possible `
Use 采用
int j =i.value;
or 要么
int j =(int) i;
Value types in c# are not-nullable unless you explicitly define them as such. 除非您明确定义c#中的值类型,否则它们不能为空。 If you want to allow nulls for an int you have to declare your variable like so:
如果要允许int为空,则必须这样声明变量:
int? i = null;
An integer is a value type, whose default value, when initialized, is 0. 整数是一种值类型,其默认值在初始化时为0。
https://msdn.microsoft.com/en-us/library/83fhsxwc.aspx https://msdn.microsoft.com/zh-CN/library/83fhsxwc.aspx
You just cannot make it null, and the compiler will not let you use an uninitialized integer. 您只是不能将其设置为null,并且编译器将不允许您使用未初始化的整数。
If you require a null to be assigned to an integer, for whatever reason, you should use a reference type Nullable. 如果出于任何原因要求将null分配给整数,则应使用引用类型Nullable。 int?
诠释? = null .
= null。 I hope this helps.
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.