什么是C#中的参数以及为什么使用它 [英] what is out parameter in c# and why we use it

查看:54
本文介绍了什么是C#中的参数以及为什么使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要使用输出参数,例如

Why do we use ouput parameters, e.g.

void f() {
    int first, next;
    read(out first, out next);
}

void read (out int first, out intnext) {
    first = console.read();
    next = console.read();
}

为什么不编写所有这些代码,为什么不使用:

Instead of writing all this code why don’t we use:

void f() {
    int first, next;
    first = console.read();
    next = console.read();
}

推荐答案

输出

当您希望一个方法返回多个值时,声明out方法很有用.使用out参数的方法仍可以返回值.一个方法可以具有多个out参数.

Declaring an out method is useful when you want a method to return multiple values. A method that uses an out parameter can still return a value. A method can have more than one out parameter.

out关键字使参数通过引用传递.这类似于ref关键字,除了ref要求在传递变量之前先对其进行初始化.要使用out参数,方法定义和调用方法都必须显式使用out关键字.

The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

尽管作为out参数传递的变量无需在传递之前进行初始化,但要求调用方法在方法返回之前分配一个值.

Although variables passed as an out arguments need not be initialized prior to being passed, the calling method is required to assign a value before the method returns.

这篇关于什么是C#中的参数以及为什么使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆