一般情况,方法的参数传递是通过值进行传递的,即一个对象作为参数传递给方法使用,该对象便进驻到该参数对象所在指针的内存空间(使用c来描述),也就是该对象在此位置创建了副本,当方法运行结束时,该副本将会被销毁;这种传递方式的使用占据了日常方法传参的绝大多数。
另一种情况是引用传递,它与值传递方式不同,对象传递给方法时对方法参数并没有影响,仍然返回的是受原始参数取值影响的方法,即methodinstance(ref _refvalue)调用 method(ref _arg)方法,但_refvalue对method无影响,返回的仍是_arg影响的结果。这点也能想到_arg必须在使用前赋值。
示例:
另一种情况是引用传递,它与值传递方式不同,对象传递给方法时对方法参数并没有影响,仍然返回的是受原始参数取值影响的方法,即methodinstance(ref _refvalue)调用 method(ref _arg)方法,但_refvalue对method无影响,返回的仍是_arg影响的结果。这点也能想到_arg必须在使用前赋值。
示例:
using system;
/******************************
* chapter:c#难点逐个击破(一)
* author:王洪剑
* date:2010-1-11
* blog:http://www.51obj.cn/
* email:walkingp@126.com
* description:重点讲解值传递方式与引用传递方式
* ***************************/
namespace wang.testref
{
public class normalclass
{
public void shownormalresult(string name)
{
name = "wang hongjian";
console.writeline(name);
}
}
public class refclass
{
/// <summary>
/// 引用类型ref类
/// </summary>
/// <param name="name"></param>
public void showrefresult(ref string name)
{
name = "wang hongjian";
console.writeline(name);
}
}
class program
{
static void main(string[] args)
{
string _name = "zhou runfa";//传递参数
#region 值传递参数方式
normalclass n = new normalclass();
n.shownormalresult(_name);//正常调用
#endregion
#region 引用传递参数方式
refclass o = new refclass();
o.showrefresult(ref _name);//结果仍然为引用传递参数
console.readkey();
#endregion
}
}
}
运行结果:
以上就是c#难点逐个击破(1):ref参数传递的内容。