.net 参考类型

.net 参考类型,.net,.net,我认为a指向MyClassInstance并且MyClassInstance等于null,那么a也必须等于null。但是a不是空的,我不明白为什么。a和MyClassInstance是对对象的引用。 更改一个引用不会更改另一个引用 var a = MyClassInstance; MyClassInstance = null; //if (a !=null){ //why } 变量a是一个引用,因此它所持有的值是某个对象的“位置”MyClassInstance也是一个参考。通

我认为
a
指向
MyClassInstance
并且
MyClassInstance
等于null,那么
a
也必须等于null。但是
a
不是空的,我不明白为什么。

a
MyClassInstance
是对对象的引用。
更改一个引用不会更改另一个引用

 var a = MyClassInstance;
    MyClassInstance = null;
    //if (a !=null){ //why }

变量
a
是一个引用,因此它所持有的值是某个对象的“位置”<代码>MyClassInstance也是一个参考。通过设置
a=MyClassInstance
它们都指向同一实例。将
MyClassInstance
设置为null仅影响该引用。它不影响对象本身,也不影响任何其他引用

因为您正在将
null
赋值给变量
MyClassInstance
,该变量刚刚引用了堆上的实际实例。您不会以任何方式接触实际的类实例

事实上,您不能直接释放类实例占用的内存;这就是垃圾收集器的作用。它查看是否有任何引用(考虑指针,但不考虑)到您的实例,如果没有保留,则从内存中删除/收集对象


也许这更清楚了:

引用类型实例的变量主要是指向内存地址的指针,因此您的示例与

var a = MyClassInstance; // Both references point to the same object
MyClassInstance = null;  // MyClassInstance now points to null, a is not affected
换句话说:
变量是引用,而不是对象本身。因此,第二个变量是引用的副本。

我认为这不是“加密”类的正确方法。你可能得打电话给内部破坏委员会。您正在将类中的某些内容设置为NULL,但actaull类仍然存在且不为NULL…a和MyClassInstance是对对象的引用吗?不到内存区域?在一天结束时,这是相同的。@Alex引用作为指针实现的事实是一个实现细节,但它是值类型,而不是引用!是的,正如名字所说:引用类型。因此,从引用类型创建变量时得到的是引用。引用本身是一种特殊的值类型,用于寻址内存。根据您的CPU,它是32位或64位的值。
int MyClassInstance = 0x1234; // points to a memory containing *your* values
int i = MyClassInstance;
MyClassInstance = 0x0;
if (i !=0x0){ //still 0x1234, because it's a copy }