C#外部参数
下面两个代码片段有什么区别?
public void foo(out classA x)
{
y = new classA();
x = y;
}
第二个:
public void foo(out classA x)
{
classA y;
x = y;
}
第二个片段是否危险,因为 x
现在拥有对此本地 y
的引用,该引用在退出 foo 后可能已经死亡?
为什么我们一般都要用“新”?
我有点困惑,因为在 C++ 中,如果第二个片段中的 x 是一个指针,则语句 x = y 甚至不会编译,因为 y 不是指针。
What is the difference between the following two code snippets?
public void foo(out classA x)
{
y = new classA();
x = y;
}
and the second:
public void foo(out classA x)
{
classA y;
x = y;
}
Is it true that the second snippet is dangerous, because x
has now a reference to this local y
, which might be already dead after exiting foo
?
Why do we have to use "new" in general?
I'm a bit confused, because in C++, if x
in the second snippet would be a pointer, the statement x = y
would not even compile since y
is not a pointer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
让我们暂时假设第二个片段是
片段,因为您写的它根本不会在C#中编译。
y
必须先分配。行clasta y;
不会像在C ++中那样在堆栈上创建clasta
的实例。它只是声明类型clasta
的变量y
。考虑到编译片段,将
out
变量分配给本地声明的变量,并且初始化的对象在任何方面都不是危险的。classa
y
指向并分配给x
的对象将保持活力,直到x
熄灭范围的范围在何处/使用/使用。Let's assume for a moment that the second snippet is
The snippet as you wrote it does not compile in C# at all.
y
has to be assigned first. The lineclassA y;
does not create an instance ofclassA
on the stack as it would in C++. It simply declares a variabley
of typeclassA
.With the compiling snippet in mind, assigning an
out
variable to a locally declared and initialized object is not dangerous in any way. TheclassA
object thaty
points to and that is assigned tox
will remain alive and well untilx
goes out of scope wherever it's declared/used.我认为您的困惑在于,在 C++ 中,第二个示例将返回对堆栈分配对象的引用。在 C# 中不会发生这种情况。
给出 C# 中的第二个示例:
无论如何,这可能无法编译,因为
y
从未分配过值。Your confusion, I think, is that in C++ the second example would return a reference to a stack-allocated object. That doesn't happen in C#.
Given your second example in C#:
This probably won't compile, anyway, because
y
is never assigned a value.不在 C# 中;您正在考虑像 C 或 C++ 这样的本地语言,它们允许使用指向局部变量的指针。在 C# 中,一切(在合理范围内)都是对托管对象的引用。一切本质上都在堆上。
Not in C#; you're thinking of native languages like C or C++ that allow one to take a pointer to a local variable. In C#, everything (within reason) is a reference to a managed object. Everything is essentially on the heap.
这并不危险,因为除非在方法返回或退出之前给出所有“out”参数的定义,否则代码将无法编译。
It is not dangerous because the code will NOT be able to be compiled unless all "out" parameters are given a definition before the method returns or exits.