方法参数ref,out的问题!
来源:互联网 发布:怎样申请做淘宝客服 编辑:程序博客网 时间:2024/06/05 19:23
对于值型变量作为方法参数时,可以有三种情况:
1.没有ref和out参数 (直接传值,不能改变实参)
2.使用ref参数 (引用传递,输入,可以改变实参)
3.使用out参数 (引用传递,输出,可以改变实参)
4.ref和out的区别在于一个需要初始化,另一个不需要...
例子:
例子(一)
using System;
using System.Collections.Generic;
using System.Text;
namespace TestRef
{
class Program
{
static void TestRef(ref int i){i+=5;}
static void Test(int i){i+=5;}
static void Main(string[] args)
{
int i1, i2;
i1 = 10;
i2 = 10;
TestRef(ref i1);//
Test(i2);//
Console.WriteLine("i1={0}, i2={1}", i1, i2);
Console.ReadLine();
}
}
}
结果:i1=15, i2=10
分析
如果不用ref那么方法Test对实参i2的改变(i2=i2+5)到那里去了?合理的解释是,传的是一个考贝.
例子(二)
为了证明其传的是一个复制本,那么设计一个新测试如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace TestRef
{
class Program
{
static void TestRef(ref int i)
{
i += 5;
}
static void Test(int i)
{
Console.WriteLine("Test中的实参为: {0}", i);
i += 5;
Console.WriteLine("Test中的实参为修改后为: {0}", i);
}
static void Main(string[] args)
{
int i1, i2;
i1 = 10;
i2 = 10;
TestRef(ref i1);//
Test(i2);//
Console.WriteLine("i1={0}, i2={1}", i1, i2);
Console.ReadLine();
}
}
}
结果:
Test中的实参为: 10
Test中的实参为修改后为: 15
i1=15, i2=10
这充分说明了,再传递实参(区别于函数定义时称为"形式参数"的称法)时是传递实参的一个复制本这个复制本与实参值相等,但处于内存中不同的位置,换言之如果单独对其中任何一个进行修改,那么这种修改的影响只会对其本身产生影响而与其它任何内在位置的其自身的复制本无关!
- 方法参数ref,out的问题!
- C#的方法参数-Params,Ref,Out
- C#的方法参数--params、ref、out
- 方法参数(params,ref,out)
- 方法参数:ref out params
- params,ref,out 参数问题
- c#之方法的out参数与ref参数
- C#总结---方法的out参数和ref参数
- 利用反射调用方法时,处理ref,out参数需要注意的问题
- 关于C#类中方法的参数 ref,out,params...
- C# 方法参数params ref out 的理解和区分
- 方法参数修饰符ref和out的区别
- C#方法的参数关键字:ref、out、params
- C#中方法参数 ref 与 out 的区别
- C#方法的参数关键字:ref、out、params
- C#方法的参数关键字:ref、out、params
- C#方法的参数关键字:ref、out、params
- C#方法的参数关键字:ref、out、params
- iBatis.Net系列(六) ResultMap
- 别了,我的阿里巴巴
- 用javascript评估用户输入密码的强度
- XML基础之 XmlDocument加载XML流
- 多线程中子线程控制进度条(参阅msdn的)
- 方法参数ref,out的问题!
- 用javascript实现页面无刷新更新数据
- VSS使用技巧-在代码里自动加入时间戳
- 在网页中实现细线边框的两种方法
- extern"c"
- 在mfc编程中创建web风格的图形用户界面(一)
- 终于去掉了location.reload()弹出的问题。
- VSFLEXGRID 数据转出到 EXCEL
- 日期时间星期的获得