简体   繁体   English

C# 对象可以为“null”但仍具有属性吗?

[英]Can a C# object be 'null' but still have properties?

I have an object for which I can print its properties (like 'name', 'id',...) in a debug console.我有一个对象,我可以在调试控制台中打印它的属性(如'name'、'id'、...)。 On the very next line, I print the object itself, and there I get 'null'.在下一行,我打印对象本身,然后得到“null”。 Kind of like this:有点像这样:

Debug.Log($"Item name is {item.name}");
Debug.Log($"Item is {item}");
if (item == null)
{
    Debug.Log("Yes, item is null!");
}

So the first line will print a correct name, the second prints 'null'.所以第一行将打印一个正确的名称,第二行打印'null'。 The third line prints "Yes, item is null!".第三行打印“是的,项目为空!”。

How is that possible?这怎么可能? (I don't know if this is relevant, but this happens in a code for Unity.) (我不知道这是否相关,但这发生在 Unity 的代码中。)

Thank you, Arnaud.谢谢你,阿诺。

That's because UnityEngine.Object overload == , != and bool operators.这是因为 UnityEngine.Object 重载==!=bool运算符。

https://docs.unity3d.com/ScriptReference/Object-operator_eq.html https://docs.unity3d.com/ScriptReference/Object-operator_eq.html

A Unity object will equal to null after it is destroyed, but you can still access part of its properties. Unity 对象在销毁后将等于 null,但您仍然可以访问其部分属性。

You can use the following condition to check whether a Unity object is completely null or not.您可以使用以下条件来检查 Unity 对象是否完全为空。

(object)item == null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM