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();

        }
    }
}

原文地址:https://www.cnblogs.com/shoneworn/p/3387387.html