C#关于ref的用法(多个实参值的传递)

按照C#默认的按值调用参数的传递机制,不能刻编写出一个方法来实现两个int类型的值交换,因为一个方法只能对应一个返回值,如何实现将两个交换的值传递回去,这里我将用到的是ref修饰符。

使用ref的单值传递(没有返回值,但是直接将实参的值做了修改,如果是两个int型做值交换,ref也将直接对其实参进行修改为值交换后的值)

ps:这里说的有些不对,但是大体思路是这个样子,看例子自己领悟吧。就是在方法中直接对原本传进来的值进行修改。不需要return

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace cxx
{
    class RefTest
    {
        public void  sqr( ref int i)   //注意ref实在所有参数类型的最前面
        {
             i = i * i;
        }

    }

    class refDemo
    {
        static void Main()
        {
            RefTest ob = new RefTest();
            int a = 10;

            Console.WriteLine("a before call:" + a);

            ob.sqr(ref a);  //还是在最前面

            Console.WriteLine("a after call:" +a);
            Console.WriteLine(@"my name is shoneworn
my blog: www.cnblogs.com/shoneworn 
welcome to my blog !");
 //对自己的博客做一下推广,同时也复习一下“@”的用法

Console.ReadKey(); } } }

 

常规单值传递(不适用ref):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace cxx
{
    class RefTest
    {
        public int sqr( int i)
        {
            return i = i * i;  //注意方法类型为int型,需要用到return来返回值
        }

    }

    class refDemo
    {
        static void Main()
        {
            RefTest ob = new RefTest();
            int a = 10;

            Console.WriteLine("a before call:" + a);

           int b = ob.sqr( a);  //用b来接收值

            Console.WriteLine("a after call:" + b);
            Console.WriteLine(@"my name is shoneworn
my blog: www.cnblogs.com/shoneworn 
welcome to my blog !");   //对自己的博客做一下推广,同时也复习一下“@”的用法


            Console.ReadKey();

        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值