方法参数(params,ref,out)

时间:2020-11-27 03:41:53

params 使用该关键字可以指定采用数目可变的参数的方法参数,可以发送参数声明中所指定类型的逗号分隔的参数列表或指定类型的参数数组,还可以不发送参数,如果未发送任何参数,则params列表的长度为0

在方法声明中的 params 关键字之后不允许任何其他参数,并且在方法声明中只允许一个 params 关键字

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

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

ref 关键字会导致通过引用传递的参数,而不是值。 通过引用传递的效果是在方法中对参数的任何改变都会反映在调用方的基础参数中。 引用参数的值与基础参数变量的值始终是一样的

out out 关键字会导致参数通过引用来传递。 这与 ref 关键字类似,不同之处在于 ref 要求变量必须在传递之前进行初始化。 若要使用 out 参数,方法定义和调用方法都必须显式使用 out 关键字

class RefExample
    {
        static void Method(ref int i)
        {
            // Rest the mouse pointer over i to verify that it is an int.
            // The following statement would cause a compiler error if i
            // were boxed as an object.
            i = i + 44;
        }

        static void Main()
        {
            int val = 1;
            Method(ref val);
            Console.WriteLine(val);

            // Output: 45
        }
    }
class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}