UnassignedReferenceException即使使用空条件运算符 [英] UnassignedReferenceException even though using the null-conditional operator

查看:807
本文介绍了UnassignedReferenceException即使使用空条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使我正在使用 我的代码:

// […]
myTarget.Preset?.ApplyTo(myTarget);

我还注意到它提到了_Preset而不是Preset(我觉得很奇怪).

I'm also noticing that it mentions _Preset instead of Preset (which I find odd).

Foo.cs中的代码:

Code in Foo.cs :

[CreateAssetMenu()]
public class Foo : ScriptableObject
{
    [SerializeField] private Preset _Preset = null;

    public Preset Preset
    {
        get { return _Preset; }
        protected set { _Preset = value; }
    }
}

我做错了什么?这不是运营商的目的吗?

What am I doing wrong? Isn't it what the operator is for?

Google搜索无济于事.

Google searches didn't help.

推荐答案

当MonoBehaviour具有字段时,仅在编辑器中[1],我们不会将这些字段设置为真实null",而是设置为"fake null"对象.我们的自定义==运算符能够检查某物是否是这些虚假的空对象之一,并且行为相应

When a MonoBehaviour has fields, in the editor only[1], we do not set those fields to "real null", but to a "fake null" object. Our custom == operator is able to check if something is one of these fake null objects, and behaves accordingly

它们可能没有重载null条件运算符.您的get属性返回假null",解释您未分配的错误(而不是NullReferenceException).

They may not have overloaded the null-conditional operator. Your get property returns the "fake null" explaining your unassigned error (and not the NullReferenceException).

自定义null检查还具有很多缺点. 它与??的行为不一致运算符,该运算符也执行null检查,但是该操作符执行纯c#null检查,并且不能被绕过以调用我们的自定义null检查.

The custom null check also comes with a bunch of downsides. It behaves inconsistently with the ?? operator, which also does a null check, but that one does a pure c# null check, and cannot be bypassed to call our custom null check.

我猜空条件运算符也会出现同样的问题.

I guess the same problem occurs for the null-conditional operator.

这篇关于UnassignedReferenceException即使使用空条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆