我创建了一个引用另一个变量B的变量B,它们都是引用类型变量.如果我将B或A设置为null,则另一个仍将指向对象实例,该实例将保持不变.
SomeClass A = new SomeClass();
SomeClass B = A;
B = null; //A still has a valid reference
Run Code Online (Sandbox Code Playgroud)
这也是事实:
SomeClass A = new SomeClass();
SomeClass B = A;
A = null; //B still has a valid reference
Run Code Online (Sandbox Code Playgroud)
但我不希望B引用A引用的实例,我希望B引用A本身.这样,如果B设置为null,则A也将设置为null.这样做有什么优雅,安全(无指针)的方式吗?或者我是否正在尝试做一些违反C#原则的事情?
谢谢.
您不能像在C++或C中那样执行此操作.只有当您使用ref参数调用方法时才能引用对象句柄:viz:
void main_method()
{
SomeClass A = new SomeClass();
secondary_method(ref A);
}
void secondary_method(ref SomeClass B)
{
B = null; // this has the side effect of clearing the A of main_method
}
Run Code Online (Sandbox Code Playgroud)