加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

有人可以解释这个涉及“通过输出”概念的C#代码的逻辑吗?

发布时间:2020-12-15 23:36:10 所属栏目:百科 来源:网络整理
导读:static int Test(out int x,int y=4) { x = 6; return x * y;}static void Main(string[] args) { int a; int z = Test(out a); Console.WriteLine(a + z);} 输出是30,但我不明白如何. 我在Test()方法中得到了,参数x将值6输出到Main()方法中,但是如果你只是
static int Test(out int x,int y=4) 
{
    x = 6;
    return x * y;
}

static void Main(string[] args) 
{
    int a;
    int z = Test(out a);
    Console.WriteLine(a + z);
}

输出是30,但我不明白如何.

我在Test()方法中得到了,参数x将值6输出到Main()方法中,但是如果你只是输出6那么它是如何发送返回值为24的?

我不知道这一切是否有意义.我想,我正在努力解决整个“传递输出”的概念.

请尝试以最简单的巴尼式方式解释这个概念.如果它过于技术性和复杂性,它可能会让我更加困惑.

解决方法

评论如下:

static void Main(string[] args) 
{
    int a;
    int z = Test(out a); // returns z as 6 * 4 = 24 and sets a = 6;
    Console.WriteLine(a + z); // 24 + 6 = 30
}

out允许开发人员通过引用传递和更新参数值,以便它反映在调用者方法中(与您的情况相同)

来自C#规格:

A parameter declared with an out modifier is an output parameter. An
output parameter does not create a new storage location. Instead,an
output parameter represents the same storage location as the variable
given as the argument in the function member or delegate invocation.
Thus,the value of an output parameter is always the same as the
underlying variable.

ref和out之间的区别在于:

? Every output parameter of a function member or anonymous function must be definitely assigned before the function member or anonymous function returns normally.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读