方法中的参数定义为out和ref的区别

一、out的用法

1,当调用有out定义的参数的方法时,其该传递的变量不需要在传递之前进行初始化,但需要被调用的方法返回之前赋值。

代码事例如下:

class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}
2,当方法重载时,其参数的变化不能是ref和out的变化。
3,当希望方法返回多个值时,声明 out 方法很有用。使用 out 参数的方法仍然可以将变量用作返回类型,但它还可以将一个或多个对象作为 out 参数返回给调用方法。
4,示例使用 out 在一个方法调用中返回三个变量。请注意,第三个参数所赋的值为 Null。这样便允许方法有选择地返回值。

代码事例如下:

    class Program
    {
        static void Main(string[] args)
        {
            int value;
            string str1, str2;
            Method(out value, out str1, out str2);
            // value is now 44
            // str1 is now "I've been returned"
            // str2 is (still) null;

            Console.WriteLine("value:" + value + ";" + "str1:" + str1 + ";" + "str2;" + str2 + ".");
            Console.Read();
        }
        static void Method(out int i, out string s1, out string s2)
        {
            i = 44;
            s1 = "I've been returned";
            s2 = null;
        }
    }

二、ref的用法

1,传递到 ref 参数的参数必须最先初始化(显式初始化),在方法中对参数所做的任何更改都将反映在该变量中。
2,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。
3,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载。
4,
代码事例如下:
class RefExample
{
    static void Method(ref int i)
    {
        i = 44;
    }
    static void Main()
    {
        int val = 0;
        Method(ref val);
        // val is now 44
    }
}
事例代码2如下:
class RefRefExample
{
    static void Method(ref string s)
    {
        s = "changed";
    }
    static void Main()
    {
        string str = "original";
        Method(ref str);
        // str is now "changed"
    }
}

 3\params:使用它可以接受任意个参数或不接受任何参数.

 

 

 

 

posted @ 2013-04-25 15:44  namehwh  阅读(166)  评论(0编辑  收藏  举报