gpt4 book ai didi

c# - 有人可以解释一下这个涉及 'passing by output' 概念的 C# 代码的逻辑吗?

转载 作者:行者123 更新时间:2023-11-30 14:07:27 27 4
gpt4 key购买 nike

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?

我不知道这一切是否有意义。我想我正在为整个“输出传递”概念而苦苦挣扎。

请尝试以最简单的 Barney 风格的方式解释这个概念。如果它过于技术化和复杂,它可能只会让我更加困惑。

最佳答案

评论如下:

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 允许开发人员通过引用传递和更新参数值,以便它反射(reflect)在调用方方法中(与您的情况下的 a 相同)

来自 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.

refout的区别在于:

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

关于c# - 有人可以解释一下这个涉及 'passing by output' 概念的 C# 代码的逻辑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com