ASP.NET(C#)ref,out,params的区别

一、out

这是一个引用传递。
原则一:当一个方法(函数)在使用out作为参数时,在方法中(函数)对out参数所做的任何更改都将反映在该变量中。
原则二:当希望方法返回多个值时,声明 out 方法非常有用。使用 out 参数的方法仍然可以返回一个值。一个方法可以有一个以上的 out 参数。
原则三:若要使用 out 参数,必须将参数作为 out 参数显式传递到方法。out 参数的值不会传递到 out 参数。
原则四:不必初始化作为 out 参数传递的变量,因为out 参数在进入方法(函数)时后清空自己,使自己变成一个干净的参数,也因为这个原因必须在方法返回之前为 out 参数赋值(只有地址没有值的参数是不能被.net接受的)。
原则五:属性不是变量,不能作为 out 参数传递。
原则六:如果两个方法的声明仅在 out 的使用方面不同,则会发生重载。不过,无法定义仅在 ref 和 out 方面不同的重载。

以下代码有效:

class MyClass
{
public void MyMethod(int i) {i = 10;}
public void MyMethod(out int i) {i = 10;}
}

以下代码无效:

class MyClass
{
public void MyMethod(out int i) {i = 10;}
public void MyMethod(ref int i) {i = 10;}
}

二、ref

ref仅仅是一个地址!!!
原则一:当一个方法(函数)在使用ref作为参数时,在方法中(函数)对ref参数所做的任何更改都将反映在该变量中。
原则二:调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。
原则三:若要使用 ref 参数,必须将参数作为 ref 参数显式传递到方法。ref 参数的值可以被传递到 ref 参数。
原则四:ref参数传递的变量必须初始化,因为ref参数在进入方法(函数)时后还是它自己,它这个地址指向的还是原来的值,也因为这个原因ref参数也可以在使用它的方法内部不操作。
原则六:如果两种方法的声明仅在它们对 ref 的使用方面不同,则将出现重载。但是,无法定义仅在 ref 和 out 方面不同的重载。

例如,以下重载声明是有效的:

class MyClass
{
public void MyMethod(int i) {i = 10;}
public void MyMethod(ref int i) {i = 10;}
}

但以下重载声明是无效的:

class MyClass
{
public void MyMethod(out int i) {i = 10;}
public void MyMethod(ref int i) {i = 10;}
}

示例

public static string TestOut(out string i)
    {
        i = "out b";
        return "return value";
    }
    public static void TestRef(ref string i)
    {
        //改变参数
        i = "ref b";
    }
    public static void TestNoRef(string refi)
    {
        // 不用改变任何东西,这个太明显了
        refi = "on c";
    }

//调用

    private void button1_Click(object sender, EventArgs e)
    {
        string outi;//不需要初始化
        MessageBox.Show(TestOut(out outi));//返回值
        //输出"return value";
        MessageBox.Show(outi);//调用后的out参数
        //输出"out b";


        string refi = "a"; // 必须初始化
        TestRef(ref refi); // 调用参数
        MessageBox.Show(refi);
        //输出"ref b";
        TestNoRef(refi);//不使用ref
        MessageBox.Show(refi);
        //输出"ref b";
    }

三、params

一个可以让方法(函数)的拥有可变参数的关键字。
原则:在方法声明中的 params 关键字之后不允许任何其他参数,并且在方法声明中只允许一个 params 关键字。
示例

public static void UseParams(params int[] list)
    {
        string temp = "";
        for (int i = 0; i < list.Length; i++)
            temp = temp + " " + list[i].ToString();
        MessageBox.Show(temp);
    }
    public static void UseParams2(params object[] list)
    {
        string temp = "";
        for (int i = 0; i < list.Length; i++)
            temp = temp + " " + list[i].ToString();
        MessageBox.Show(temp);
    }

调用如下:

    private void button1_Click(object sender, EventArgs e)
    {
        UseParams(1, 2, 3);//看参数是3个
        UseParams(1, 2); //看参数是2个,可变吧
        UseParams2(1, 'a', "test");
        int[] myarray = new int[3] { 10, 11, 12 };
        UseParams(myarray); //看也可以是容器类,可变吧:)
    }

原文地址:https://www.cnblogs.com/hakuci/p/1882183.html