c# - 引用 C# 中的引用

标签 c# reference

假设我创建了一个引用另一个变量 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/

相关文章:

c# - 将 Combobox 绑定(bind)到一个枚举,一个枚举元素除外

c# - DateTimeFormatInfo.InvariantInfo 与 CultureInfo.InvariantCulture

c++ - 通过引用 C++ 初始化指针数组

c++ - "non-const lvalue reference to type cannot bind"引用错误(类型&)但指针错误(类型*)

c# - 为多个项目指定代码分析输出文件

c# - 你如何映射一个组件,它也是 NHibernate hbm xml 中的主键(或在 fluent-nhibernate 类映射中)?

c# - Windows 应用商店应用程序中的文件关联,我做错了什么?

c++ - 从类型为 'char*&' 的临时对象初始化类型为 'char*' 的非常量引用

C++ 协变和引用

html - 具有 set Input() 任意类型的可重用组件是一个好的实践吗?