为什么参数值不增加和参考参数增量? [英] Why value by parameter not increment and reference parameter increment ?

查看:92
本文介绍了为什么参数值不增加和参考参数增量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program
    {
        public static void value(int num)
        {
            num++;
        }
        public static void reference(ref int num)
        {
            num++;
        }
 
        static void Main(string[] args)
        {
            int num;
            Console.Write("Enter a number:\t");
            num = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\n\n\tValue Type");
            Console.WriteLine("----------------");
            Console.Write("\nPrevious Value:\t{0}", num);
            Program.value(num);
            Console.Write("\nCurrent Value:\t{0}", num);
 
            Console.WriteLine("\n\n\n----------------");
            Console.WriteLine("\tReference Type");
            Console.WriteLine("--------------------");
            Console.Write("\nPrevious Value:\t{0}", num);
            Program.reference(ref num);
            Console.Write("\nCurrent Value:\t{0}", num);
            Console.ReadLine();
        }
    }





我的尝试:



有人能解释一下这背后的实际原因吗?



What I have tried:

can someone explain me what actual reason behind this ?

推荐答案

因为它是按照定义 :(粗略地说)一个方法只能改变通过引用传递的参数。例如,请参阅传递参数(C#编程指南)| Microsoft Docs [ ^ ]。
Because it is so by definition: (roughly speaking) a method can only change parameters passed by reference. See, for instance Passing Parameters (C# Programming Guide) | Microsoft Docs[^].


按值和引用传递是编程语言的基本属性。



请参阅评估策略 - 维基百科 [ ^ ]和传递参数(C#编程指南)| Microsoft Docs [ ^ ]。
Passing by value and reference are fundamental properties of programming languages.

See for example Evaluation strategy - Wikipedia[^] and Passing Parameters (C# Programming Guide) | Microsoft Docs[^].


这篇关于为什么参数值不增加和参考参数增量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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