C# 关键字ref 和out 的详细区别

refout 的详细区别

refout都是C#中的关键字,所实现的功能也差不多,都是指定一个参数按照引用传递。

对于编译后的程序而言,它们之间没有任何区别,也就是说它们只有语法区别。

总结起来,他们有如下语法区别:

1ref传进去的参数必须在调用前初始化,out不必,即:
int i;
SomeMethod( ref i );//语法错误
SomeMethod( out i );//通过

2ref传进去的参数在函数内部可以直接使用,而out不可:
public void SomeMethod(ref int i)
{
   int j=i;//通过
   //...
}
public void SomeMethod(out int i)
{
   int j=i;//语法错误

}


3ref传进去的参数在函数内部可以不被修改,但out必须在离开函数体前进行赋值。

ref在参数传递之前必须初始化;而out则在传递前不必初始化,且在 ... 值类型与引用类型之间的转换过程称为装箱与拆箱。


总结:
应该说,系统对ref的限制是更少一些的。out虽然不要求在调用前一定要初始化,但是其值在函数内部是不可见的,也就是不能使用通过out传进来的值,并且一定要在函数内赋一个值。或者说函数承担初始化这个变量的责任。


数组型参数:以params修饰符声明。

params关键字用来声明可变长度参数列表。方法声明中只能包含一个params参数,并且只能放在参数列表的最后

Public void F( int n, params int[ ] args )

{ …… }


参考代码:

Demo
using System;
using System.Collections.Generic;
using System.Text;

namespace Con_1
{
    
class Class1
    {
        
static void Main(string[] args)
        {
            
int n1 = 5;
            MyFun(n1); 
//一、普通方法
            Console.WriteLine(n1);

            
int n2 = 5;
            MyRef(
ref n2); //二、带ref参数的方法
            Console.WriteLine(n2);

            
int n3 = 5;
            MyOut(
out n3); //三、带out参数的方法
            Console.WriteLine(n3);

            MyParams(
"xg"1122); //四、带params参数的方法
            MyParams("xg",11223344);
        }
        
//一、普通方法
        public static void MyFun(int i)
        {
            i 
= i + 5;
        }
        
//二、带ref参数的方法
        public static void MyRef(ref int i)
        {
            i 
= i + 5;
        }
        
//三、带out参数的方法
        public static void MyOut(out int i)
        {
            i 
= 5 + 5;
        }

        
//四、带params参数的方法
        
// params 参数对应的是一个一维数组: int、string等
        
// 在方法的参数列表中只能有一个params 参数
        
// 当有多个参数时,params 参数必须放在参数列表的最后
        public static void MyParams(string str,params int[] arr)
        {
            
foreach(int n in arr)
            {
               Console.WriteLine(n);
            }
        }
    }
}


原文地址:https://www.cnblogs.com/xugang/p/1684088.html