[C#] 值参数,引用参数和输出参数: 关键字 ref 和 out 用法

值参数 (Value Parameter)

省略,估计没什么新意。

引用参数 (Reference Parameter)

C#有4种引用类型:

String 字符串
All arrays, 全部数组,即使元素为值类型也不例外
Class 类
Delegates 委托

这和C++ 中的引用的概念是一样的,C++ 使用 &符号表示引用。
下例中的 f1不使用引用也是ok的,因为类本来就是引用类型。

namespace CodeSamples
{
    class MyClass
    {
        public int Val = 20; // Initialize field to 20.
    }
    class Program
    {
        static void MyMethod(ref MyClass f1, ref int f2)
        {
            f1.Val = f1.Val + 5; // Add 5 to field of f1 param.
            f2 = f2 + 5; // Add 5 to second param.
            Console.WriteLine("f1.Val: {0}, f2: {1}", f1.Val, f2);
        }
        static void Main()
        {
            MyClass a1 = new MyClass();
            int a2 = 10;
            MyMethod(ref a1, ref a2); // Call the method.
            Console.WriteLine("a1.Val: {0}, a2: {1}", a1.Val, a2);
            Console.Read();
        }
    }
}

输出:

f1.Val: 25, f2: 15
a1.Val: 25, a2: 15

如果加ref修饰符,则实参和形参都要同步加ref修饰符,否则出错。

输出参数 (Output Parameter)

输出参数使用out关键字,和ref类似,实参和形参同步加out

outref的区别是,out修饰的参数初始值传进方法时被忽略, 也就是说,被out修饰的参数在传进方法之前,是不需要初始化不需要赋值的,反正初值没有用处。

也因为同样的原因,这种参数在赋值之前不能读值:

public void Add2( out int outValue )
{
    int var1 = outValue + 2; // 错误!方法未赋值给output parameter之前不能读取
} 

用法:

class MyClass
{
    public int Val = 20; // Initialize field to 20.
}
class Program
{
    static void MyMethod(out MyClass f1, out int f2)
    {
        f1 = new MyClass(); // Create an object of the class.
        f1.Val = 25; // Assign to the class field.
        f2 = 15; // Assign to the int param.
    }
    static void Main()
    {
        MyClass a1 = null;
        int a2;
        MyMethod(out a1, out a2); // Call the method.
    }
}

从C# 7开始,变量在用作out参数前,不再需要预先声明,下面的第(1),(2) 条语句可省略,直接使用 (3) 就可以,但是等价于 (1) + (2) + (3):

    MyClass a1 = null; // 1.
    int a2; // 2.
    MyMethod(out a1, out a2); // 3. Call the method.

[1] Illustrated C# 7

猜你喜欢

转载自blog.csdn.net/ftell/article/details/81873311
今日推荐