C# reference variable, does making one null make the other null?

≯℡__Kan透↙ 提交于 2019-12-24 05:50:56

问题


I have a question about how C# works.

m_MyClass = new MyClass();
Dispatcher.m_MyClass = m_MyClass;

If I set m_MyClass = null, will that automatically make Dispatcher.m_MyClass null?


回答1:


No. Assigning a different value to a variable of a reference has no effect on other references.

Only modifying fields of an instance or using properties or methods which modify those fields will have an effect:

m_MyClass = new MyClass();
Dispatcher.m_MyClass = m_MyClass;

m_MyClass.MyProp = null;
// Dispatcher.m_MyClass.MyProp == null



回答2:


No. The variable assignment is assigning a copy of the reference by value. Changing the variable after the assignment will not affect the Dispatcher.m_MyClass field/property.



来源:https://stackoverflow.com/questions/18109874/c-sharp-reference-variable-does-making-one-null-make-the-other-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!