记录ref的用法如下:
public class ValueTransfer { private int num1 = 1; private Vector2 _vector2; public void Main() { _vector2 = Vector2.Zero; SetValueNoRef(num1); PrintValue(); // num1 = 1 SetValue(ref num1); PrintValue(); // num1 = 22 SetVector2NoRef(_vector2); PrintVector2(); // vector2.x = 0 , vector2.y = 0 SetVector2(ref _vector2); PrintVector2(); // vector2.x = 3 , vector2.y = 4 } private void SetValueNoRef(int pValue) { pValue = 10; } private void SetValue(ref int pValue) { pValue = 22; } private void PrintValue() { Console.WriteLine("num1 = {0}",num1); } private void SetVector2NoRef(Vector2 vector2) { vector2 = new Vector2(1,2); } private void SetVector2(ref Vector2 vector2) { vector2 = new Vector2(3,4); } private void PrintVector2() { Console.WriteLine("vector2.x = {0} , vector2.y = {1}" , _vector2.X , _vector2.Y); } }
此示例展示函数中,只是传入了值,还是把它原有地址传入,当操作这个变量时,所产生的结果就不一样。
                    
                
                
            
        
浙公网安备 33010602011771号