C#基础 函数的值传递方式

C#函数的值所谓的几种传递方式

一、值传递

是c#默认的值传递方式,原理就是将你的实参复制一份到传给函数的形参,调用时新创立一个存储位置,两者位置不同,互不影响。

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int a = 5;
            Program hh = new Program();
            hh.test(a);           
        }
        public void test(int a)
        {
            Console.WriteLine("运算前:"+ a);
            a *= a;
            Console.WriteLine("运算后:"+a);
        }
    }
}

输出:

运算前:5
运算后:25

二、引用传递(ref)

这种传递模式故名思意,即使引用你原来那个值所存储的位置,去引用它得到使用。直接使用原来的数据,不会创建新的存储位置,若进行运算会对数据有更改,这里使用 ref 关键字进行引用值传递

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int a = 5;
            Program hh = new Program();
            Console.WriteLine("函数调用前:" + a);
            hh.test(ref a);
            Console.WriteLine("函数调用后:" + a);
        }
        public void test(ref int a)
        {
            a *= a;
            Console.WriteLine("函数运行:" + a);
        }
    }
}

输出:

函数调用前:5
函数运行:25
函数调用后:25

三、输出传递(out)

输出传递和引用传递类似,但不完全相同,其区别是,用 out 关键字进行输出传递可以传输很多个值。不同于return只返回一个。输出传递不返回到函数而是直接返回原来的存储位置的数据。

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int a = 5;
            int b = 5;
            Program hh = new Program();
            Console.WriteLine("函数调用前:" + a);
            Console.WriteLine("函数调用前:" + b);
            hh.test(out a,out b);
            Console.WriteLine("函数调用后:" + a);
            Console.WriteLine("函数调用前:" + b);
        }
        public void test(out int a ,out int b)
        {
            int c= 10;
            a = c;
            b = c;
            a *= a;   
            b *= b;
        }
    }
}

输出

函数调用前:5
函数调用前:5
函数调用后:100
函数调用前:100

 欢迎大家交流和讨论~~

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值