• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
激情 希望 斗志昂扬
Records of growth process 专注微软技术
博客园    首页    新随笔    联系   管理    订阅  订阅

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

使用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的值改变
}
}

 

 

 

 

使用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的例子吧:

 

out使用的实际例子哦
   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);
        }
    }

 

posted @ 2009-04-11 12:03  贤  阅读(509)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3