美文网首页
每日一学15——Unity C# 中 ??、 ?、 ?: 、?.

每日一学15——Unity C# 中 ??、 ?、 ?: 、?.

作者: ShawnWeasley | 来源:发表于2020-07-09 18:00 被阅读0次

学习来源:https://blog.csdn.net/qq_42453390/article/details/90403344

用的时候注意C#版本~
这里主要说一下??空合并运算符,??相当于是一个非空判断,如果左侧为空则返回右侧内容(但是组合运算时从右向左,用多个??时建议加括号处理)。比如下面的场景:

        void Start()
        {
            Test(null);
        }

        void Test(string name)
        {
            string animalName = name ?? "animal";
            Debug.Log(animalname);
        }

当然了除了普通类型判断主要还是用于自建类的判断,可以在将函数提供给别人用的时候,进行一下判断:

        void Start()
        {
            Duck duck = null;
            Test(duck);
        }

        void Test(Animal animal)
        {
            Animal animal1 = animal ?? new Animal();
        }

        class AnimalObject { public string Name; }

        class Animal { public AnimalObject AnimalObject; }

        class Duck : Animal { }

        class Cat : Animal { }

还有NULL检查运算符(?.)也很好用:

        void Start()
        {
            Duck duck = new Duck();
            Test(duck);
        }

        void Test(Animal animal)
        {
            //string animalName = animal?.AnimalObject.Name;//报错
            string animalName = animal?.AnimalObject?.Name;//不报错,返回null
            Debug.Log(animalName);
        }

        class AnimalObject { public string Name; }

        class Animal { public AnimalObject AnimalObject; }

        class Duck : Animal { }

        class Cat : Animal { }

相关文章

网友评论

      本文标题:每日一学15——Unity C# 中 ??、 ?、 ?: 、?.

      本文链接:https://www.haomeiwen.com/subject/isiscktx.html