c#中的关键字out是什么意思

如题所述

在C#编程中,有时会希望使用引用形式从方法中接收值,但不传入。例如,可能有一个执行某种功能的方法,比如打开在引用形参中返回成功或失败代码的网络套接字。在此情况下,没有信息传递方法,但有从方法传出的信息。这种情况存在的问题是在调用前必须将ref形参初始化为一个值。因此,要使用ref形参,需要赋予实参一个哑元值,从而可以满足这一约束。C#中out形参就可以解决此类问题。

out形参类似于ref形参,但它只能用来将值从方法中传出。在调用之前,并不需要为out形参的变量赋予初始值。在方法中,out形参总是被认为是未赋值的,但在方法结束前必须赋于形参一个值。因此,当调用方法后,out形参引用的变量会包含一个值。

下面是一个使用out形参例子。方法RectInfo()返回已知边长的矩形面积。在形参isSquare中,如果矩形是正方形,返回true,否则返回false。因此,RectInfo()向调用者返回两条信息。

using System;
class Rectangle{
    int side1;
    int side2;
    public Rectangle(int i, int j){
        side1 = i;
        side2 = j;
    }
    // Return area and determine if square.
    public int RectInfo(out bool isSquare){
        if (side1 == side2) 
            isSquare = true;
        else 
            isSquare = false;
        return side1 * side2;
    }
}
 
class OutDemo{
    static void Main(){
        Rectangle rect = new Rectangle(10, 23);
        int area;
        bool isSqr;
        area = rect.RectInfo(out isSqr);
        if (isSqr) 
            Console.WriteLine("rect is a square.");
        else 
            Console.WriteLine("rect is not a square.");
        Console.WriteLine("Its area is " + area + ".");
        Console.ReadKey();
    }
}

温馨提示:答案为网友推荐,仅供参考
相似回答