Unity3d-C#之语法特性

本文介绍了Unity3D中C#的运算符、ref和out关键字的使用。运算符部分重点讲解了null合并运算符,它用于确定可为null类型和引用类型的默认值。ref关键字允许通过引用传递参数,实现对原参数的直接修改。而out关键字同样用于参数传递,但强调接收方法必须初始化变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

?? 运算符:http://msdn.microsoft.com/zh-cn/library/ms173224(v=VS.100).aspx

?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。 如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。

下面代码源于Unity3d 4.6UI系统源码:UI / UnityEngine.UI / EventSystem / Raycasters / PhysicsRaycaster.cs

 public override Camera eventCamera
        {
            get
            {
                if (m_EventCamera == null)
                    m_EventCamera = GetComponent<Camera>();
                return m_EventCamera ?? Camera.main;
            }
        }

ref 关键字: http://msdn.microsoft.com/zh-cn/library/14akc2c7.aspx

ref 关键字通过引用(而非值)传递参数。 通过引用传递的效果是,对所调用方法中的参数进行的任何更改都反映在调用方法中

下面代码源于:UI / UnityEngine.UI / UI / Core / SetPropertyUtility.cs

        public static bool SetClass<T>(ref T currentValue, T newValue) where T : class
        {
            if ((currentValue == null && newValue == null) || (currentValue != null && currentValue.Equals(newValue)))
                return false;

            currentValue = newValue;
            return true;
        }

out 关键字通过引用传递参数:http://msdn.microsoft.com/zh-cn/library/t3c3bfhx.aspx

下面代码源于:UI / UnityEngine.UI / EventSystem / InputModules / PointerInputModule.cs
     protected bool GetPointerData(int id, out PointerEventData data, bool create)
        {
            if (!m_PointerData.TryGetValue(id, out data) && create)
            {
                data = new PointerEventData(eventSystem)
                {
                    pointerId = id,
                };
                m_PointerData.Add(id, data);
                return true;
            }
            return false;
        }
隐式类型 var:http://msdn.microsoft.com/zh-cn/library/bb383973.aspx
下面代码源于:UI / UnityEngine.UI / EventSystem / InputModules / PointerInputModule.cs
   protected static PointerEventData.FramePressState StateForMouseButton(int buttonId)
        {
            var pressed = Input.GetMouseButtonDown(buttonId);
            var released = Input.GetMouseButtonUp(buttonId);
            if (pressed && released)
                return PointerEventData.FramePressState.PressedAndReleased;
            if (pressed)
                return PointerEventData.FramePressState.Pressed;
            if (released)
                return PointerEventData.FramePressState.Released;
            return PointerEventData.FramePressState.NotChanged;
        }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值