C# 中的堆栈和空值

Stack and Null in C#

public Class MyClass
{
int a;
}

Class Something
{

int Main ()
{

Var c = new MyClass();
c = Null;   //Possible

}

}

在 C# 中,Var 只能存储在堆栈中,因此您必须在定义变量后立即初始化 var,因为编译器不知道将 Null 存储在 Stack.From 上面的代码将 null 存储在 c( Var c in Main function of something class) 是可能的。那么,C# Compiler 是否知道如何在堆栈上存储 null 或是否有任何其他解释?

var c = null; 

这将导致错误,因为编译器不知道将 null 绑定到哪个 type。你可以做类似

的事情
var c = default(MyClass);

我认为这与堆栈或堆无关,而仅与类型推断有关。

在将 Var 初始化为 null 的情况下,编译器无法推断变量的预期类型,因此您需要提供类型信息。

为了完整起见

Var can only be stored on stack

事实并非如此。存储在堆栈上(在托管代码中)的是值类型,而引用类型存储在堆上。 因此,在您的情况下,变量 c 未存储在堆栈中,而是进入堆,并且 null 是绝对允许的。 但是在某些情况下,您可以将 null 存储在值类型变量中,它是一个 nullabe 值类型,它是一个结构。您可以将其视为存储在堆栈中。

来自this

Structs only go on the temporary memory pool, aka "the stack", when they are local variables or temporaries

在这种情况下,null 以特殊方式处理,作为未设置标志 hasValue 的可空类型。 link