C# 自动引用分配 - 使引用为空

标签 c# reference variable-assignment

Unity3D 中的 C# 脚本环境(在 Mono 下运行)在销毁对象时具有良好的行为。所有指向被销毁对象的引用都会自动变为 null :

    GameObject ref1 = (GameObject)Instantiate(obj);
    GameObject ref2 = ref1;

    if (ref1 != null)
        Debug.Log("ref1 is not null");

    DestroyImmediate(ref1);

    if (ref1 == null)
        Debug.Log("ref1 is null");

    if (ref2 == null)
        Debug.Log("ref2 is null");    

输出:

    ref1 is not null
    ref1 is null
    ref2 is null

关于如何实现这一点有什么想法吗?

谢谢

最佳答案

也许相等运算符已被覆盖?这可以解释您的评论:“只是发现如果 ref1 和 ref2 不是 GameObject 而是 System.Object,那么它就不会工作。”

关于C# 自动引用分配 - 使引用为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2128964/

相关文章:

mysql - 使用groovy域类引用其他表中的字段创建mysql表

c# - Xamarin 将 View 添加到布局但在屏幕上不可见

C++ 通过引用传递指针并分配默认值

c# - FxCop - CA1034 错误 - 为什么?

c# - 通过 ref : cannot convert from 'Foo' to 'ref IFoo' 传递实现

c# - 如何从 foreach 循环中修改 foreach 迭代变量?

python - Z3 Python : ordering models and accessing their elements

C++ map<K,T> 初始化

c# - 如何知道一个事件有多少个事件处理程序?

c# - 使 ASP.NET 身份在 Mongo 中存储用户数据(托管在 Heroku 上)