如何在 C# 中将 int 变量分配给空?

How to assign int variable to empty in c#?

如何在 C# 中将 int 变量赋值给 empty?

目前变量默认为0

声明的变量:

public int Timesaday { get; set; }

我尝试使用 Nullable.. public int? Timesaday { get; set; }

预期结果,变量不应分配默认值 = 0。默认值应为空。

所有 Nullable 类型都初始化为 null

public static int ? Timesaday
{
    get;
    set;
}

public static void Main()
{
    Console.WriteLine(Timesaday == null);
}

输出

True

Demo here


如果您查看 Nullable<T> referencesource.microsoft.com 的源代码,您会发现除非您通过构造函数传入值,否则它将是 HasValue == false 而没有值

public struct Nullable<T> where T : struct
{
    private bool hasValue; 
    internal T value;

    [System.Runtime.Versioning.NonVersionable]
    public Nullable(T value) {
        this.value = value;
        this.hasValue = true;
    }        

...

 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,而不是数据类型通常可能的值。

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