C#方法参数:params,ref,out,可选参数,命名参数

1.params

params 关键字可以指定在参数数目可变处采用参数的方法参数,在方法声明中只允许一个 params 关键字,并且是最后一个参数。

using System;

class App
{
    
public static void UseParams(params object[] list)
    
{
       
for (int i = 0; i < list.Length; i++)
      
{
            Console.WriteLine(list[i]);
      }

    }

     static void Main()
    
{
        
// 一般做法是先构造一个对象数组,然后将此数组作为方法的参数
        object[] arr = new object[3100'a'"keywords" };
        UseParams(arr);

        
// 而使用了params修饰方法参数后,我们可以直接使用一组对象作为参数
        
// 当然这组参数需要符合调用的方法对参数的要求
        UseParams(100'a'"keywords");
        Console.Read();
    }

 }

2.ref和out

ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。

  1. 若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。
  2. 传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。
  3. 属性不是变量,因此不能作为 ref 参数传递。
  4. 尽管 ref 和 out 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的。如果尝试这么做,将导致不能编译该代码。
  5. 如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载。
示例
static void Main(string[] args)
{
int i = 0;
RefMethod(
ref i); //调用时也需要ref关键字
Console.WriteLine("i=" + i);//这里打印的结果为i=1,说明ref关键字可以改变i的值。
int j;
OutMethod(
out j); //调用时也需要out关键字
Console.WriteLine("j=" + j);
Console.Read();
}

public static void RefMethod(ref int i) //参数使用了ref关键字
{
i
++;
}
public static void OutMethod(out int i) //参数使用了out关键字
{
i
= 0; //out参数规定,参数在方法体内必须被初始化。
i++;
}
 
     ///Ref参数的实例
    protected void valueParams(string str)
        {
            str = "251";
        }
        protected void valueParams(ref string str)
        {
            str = "250";
        }
    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string str = "249";
                valueParams(str);
                Response.Write("按值传递:"+str);//249
                valueParams(ref str);
                Response.Write("Ref参数:"+str);//250//ref改变了参数的值
            }
        }

 3.可选参数

        /// <summary>
        /// 可选参数(声明方法时,将常量值赋给参数,调用时就可选)
        /// </summary>
        /// <returns>dddddd</returns>
        public string SwapParams(string first,string second,string third="jie")
        {
            return first + second + third;
        }

 //调用

SwapParams("diao","jun");

4.命名参数

        /// <summary>
        /// 命名参数(调用者可显式指定参数名,并为该参数赋一个值)
        /// </summary>
        /// <returns></returns>
        public string SwapMingMing(string first,string second=default(string),string third=default(string))
        {
            return first + second + third;
        }

//调用

SwapMingMing(first: "diao",third:"jie",second:"jun");

原文地址:https://www.cnblogs.com/paste/p/1856339.html