如何在 c# 中将空值设置为 int

本文关键字:空值 设置 int | 更新日期: 2023-09-27 18:36:29

int value=0;
if (value == 0)
{
    value = null;
}

如何将value设置为上述null

任何帮助将不胜感激。

如何在 c# 中将空值设置为 int

在 .Net 中,不能将null值分配给int或任何其他结构。相反,请使用 Nullable<int> 或简称int?

int? value = 0;
if (value == 0)
{
    value = null;
}

延伸阅读

  • 可为空的类型(C# 编程指南)

此外,不能在条件赋值中使用"null"作为值。 例如...

bool testvalue = false;
int? myint = (testvalue == true) ? 1234 : null;

失败,并显示:Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'.

因此,您还必须强制转换空值...这有效:

int? myint = (testvalue == true) ? 1234 : (int?)null;

更新(2021 年 10 月):

从 C# 9.0 开始,您可以使用"目标类型"条件表达式,该示例现在将工作,因为 c# 9 可以通过在编译时计算表达式来预先确定结果类型。

不能将int设置为 null 。请改用可为空的 int (int?

):
int? value = null;

int 不允许 null,使用-

int? value = 0  

或使用

Nullable<int> value
 public static int? Timesaday { get; set; } = null;

 public static Nullable<int> Timesaday { get; set; }

 public static int? Timesaday = null;

 public static int? Timesaday

或者只是

 public static int? Timesaday { get; set; } 

    static void Main(string[] args)
    {

    Console.WriteLine(Timesaday == null);
     //you also can check using 
     Console.WriteLine(Timesaday.HasValue);
        Console.ReadKey();
    }

null 关键字是表示 null 引用的文本,该引用不引用任何对象。在编程中,可为空的类型是某些编程语言的类型系统的一项功能,它允许将值设置为特殊值 NULL,而不是数据类型的通常可能值。

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nullhttps://en.wikipedia.org/wiki/Null

将整数变量声明为可为空例如:int? variable=0; variable=null;