输出参数out和引用参数ref区别(代码解释说明)

本文详细介绍了C#中的ref和out参数的使用方法及其区别。通过具体示例展示了如何利用这两种参数来修改方法外部的变量值,并强调了它们在参数传递前是否需要初始化的不同要求。
ContractedBlock.gifExpandedBlockStart.gif使用ref的一段代码
using System;
class M
{
public void F(ref int i)
{
i
=3;
}
}
class Test
{
int i=0;//要作为引用参数传递的变量必须明确赋值
static void Main()
{                           
//不能把int i=0;放在这里赋值,会报错说Test不包含i定义。
Test t=new Test();
Console.WriteLine(
"the value of i is:{0}",t.i);
M mm
=new M();
mm.F(
ref t.i);//作为引用参数传递
Console.WriteLine("now the value of i is :{0}",t.i);//i的值改变
}
}

 

 

 

 

ContractedBlock.gifExpandedBlockStart.gif使用out的一段类似代码
class M
    {
        
public void F(out int i)                     //这个方法和ref的方法都是一样,没什么不同
        {
            i 
= 8;//返回前必须明确赋值
        }
    }
    
class Test
    {
        
int i;               //不用赋初值,这就是out和ref的区别,但声明还是要的
        public static void Main()
        {
            Test t1 
= new Test();
            Console.WriteLine(
"the value of i is :{0}", t1.i);   //输出是0;
            M m1 = new M();
            m1.F(
out t1.i);//i作为输出参数传递 ,输出是8
            Console.WriteLine("now value of i is :{0}", t1.i);
        }
    }

 

 

 

下面说下相同点:

1:out关键字修饰的方法参数是输出参数,和与引用类型(别忘记了ref是引用类型哦)类似,输出型参数也不创建新的内存区域。

 

 

不同点:

1:在传递out变量之前可以不对变量进行初始化,而在方法返回之前,必须给out参数赋值(不明白看上面代码的解析罗),ref 要求变量必须在传递之前进行初始化。

 

out关键字作用:

 

 一般的方法就只返回一个参数,当希望方法返回多个值时,声明 out 方法很有用。
例子:


static void Method(out int i, out string s1, out string s2) 
   {  i 
= 44;   
     s1 
= "I've been returned";   

     s2 = null;    

}

也就是在方法返回后给事前声明的变量在方法中赋值了

 

 看多一条out的例子吧:

 

ContractedBlock.gifExpandedBlockStart.gifout使用的实际例子哦
   class TestOut
    {
        
static void SplitPath(string path, out string dir, out string name)
        {
            
int i = path.Length;
            
//以下计算路径的节点
            while (i > 0)
            {
                
char ch = path[i - 1];
                
if (ch == '\\' || ch == '/' || ch == ':')
                    
break;
                
else
                    i
--;
            }
            dir 
= path.Substring(0, i);   //在path的字符串中从第0个开始取出前i个字符,并赋值到dir上
            name = path.Substring(i);//在path的字符串中取出后i个字符,并赋值到name上
        }
        
static void Main(string[] args)
        {
            
string dir, name;
            SplitPath(
"c:\\learncs\\hello.txt"out dir, out name);
            Console.WriteLine(dir);
            Console.WriteLine(name);
        }
    }

 

转载于:https://www.cnblogs.com/xianspace/archive/2009/04/11/1433602.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值