假设我创建了一个引用另一个变量 A 的变量 B,它们都是引用类型变量。如果我将 B 或 A 设置为 null,另一个仍将指向对象实例,该实例将保持不变。
SomeClass A = new SomeClass();
SomeClass B = A;
B = null; //A still has a valid reference
这也是对的:
SomeClass A = new SomeClass();
SomeClass B = A;
A = null; //B still has a valid reference
但我不希望 B 引用 A 引用的实例,我希望 B 引用 A 本身。这样,如果 B 设置为 null,则 A 也将设置为 null。有没有优雅、安全(无指针)的方式来做到这一点?还是我试图做一些违反 C# 原则的事情?
谢谢。
最佳答案
您不能像在 C++ 或 C 中那样执行此操作。唯一可以引用对象句柄的情况是在调用带有 ref
参数的方法时:即:
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
}
关于c# - 引用 C# 中的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20098263/