您的位置:首页 > 编程语言 > C#

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

2013-10-25 10:09 288 查看
按照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();

}
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: