gpt4 book ai didi

c# - 不能将基本类型的变量作为输出参数传递?

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

刚刚注意到这不起作用:

var dict = new Dictionary<int, XElement>();
XContainer element;
//...
if (dict.TryGetValue(idx, out element)) { //...

然后我试了一下:

class A { }
class B : A { }

class Program {
static void Main() {
A a;
a = Ret(); // no error, ok
Ref(ref a); // compiler error, ok...
Out(out a); // compiler error, lolwut?!
}
static B Ret() { return null; }
static void Ref(ref B b) { }
static void Out(out B b) { b = null; }
}

为什么我在最后一次调用中遇到编译器错误?

编辑:好吧,据我所知,“out”是变相的“ref”,因此它可以被其他函数或线程共享和更改。但实际上,'out' 不应该是一种从函数返回多个值的方法吗?因为如果是这样,它似乎并不擅长。 如果共享会产生问题,那就不要共享。只需在函数的开头创建一个隐藏变量,然后使用它。我的意思是:

static void Out(out B b) {
B bHidden; // compiler generated;
// all references to b are replaced with bHidden;
b = bHidden;
}

有什么理由不能这样做吗?现在对我来说似乎很安全......

最佳答案

as I understand from the answers 'out' is 'ref' in disguise, so it can be shared and changed by other functions or threads. But really, isn't 'out' supposed to be a way to return multiple values from a function? Because if so, it doesn't seem to be good at it. If sharing creates problems, then don't share. Just create a hidden variable at the start of the function, and work with it. I mean:

static void Out(out B b) 
{
B bHidden; // compiler generated;
// all references to b are replaced with bHidden;
b = bHidden;
}

Is there any reason it can't be done this way? It seems safe to me now...

出于显而易见的原因,这样的系统称为“复制”系统。可以那样做,但这样做会产生一些有趣的问题。例如:

void M()
{
int b = 1;
try
{
N(out b);
}
catch (FooException)
{
Console.WriteLine(b);
}
}

void N(out int c)
{
c = 123;
P();
c = 456;
}

void P()
{
throw new FooException();
}

程序的输出是什么?应该是什么?

下一个问题:你希望out的行为与ref一致还是不一致?如果你想让它不一致,那么恭喜你,你刚刚给语言添加了一个高度困惑的不一致。如果你想让它保持一致,那么你需要让 ref 使用“copy in copy out”语义,这会在性能和正确性方面引入许多问题。

我可以整天继续列举引用语义和复制语义之间的差异,但我不会。我们拥有的系统就是我们拥有的系统,所以要学会使用它。

此外,如果您想从一个方法返回多个值,不要使用输出参数。这在 2001 年可能是明智之举,但现在是 2012 年,我们有更多工具供您使用。如果你想返回两个值:

  • 返回一个元组
  • 将代码重构为两个方法,每个方法返回一个值
  • 如果这两个值是一个值类型和一个 bool 值,则返回一个可为 null 的值类型。

关于c# - 不能将基本类型的变量作为输出参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9341887/

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