为什么我不能在输出参数中传递未分配的对象变量然后分配它
在 C# 中,为什么我不能在 out
参数中传递未分配的对象变量,然后对其进行分配?
如果我尝试这样做,则会出现编译器错误:“无法在此范围内声明局部变量
,因为它会给
...”
例如。
void MyMethod(int x, out MyObject mo) { **MyObject** mo = new MyObject(); }
// in some other scope:
MyObject mo;
MyMethod(1, out mo);
编辑:我现在可以看到我的错误了。我已将上面的代码更改为我的代码。星号中的 MyObject
不应该存在。
In C#, why can't I pass an unassigned object variable in an out
parameter and then assign it?
If I try to do this, there is a compiler error: "Local variable <xyz>
cannot be declared in this scope because it would give a different meaning to <xyz>
..."
eg.
void MyMethod(int x, out MyObject mo) { **MyObject** mo = new MyObject(); }
// in some other scope:
MyObject mo;
MyMethod(1, out mo);
EDIT: I can see my mistake now. I have changed the above code to what mine was. The MyObject
in asterisks should not be there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您最初发布的代码不正确,但现在我们看到问题实际上就在这里:
您正在创建一个新的局部变量
mo
,它“隐藏”了参数mo
。很高兴我们最终到达了那里:-)
The code you posted original was incorrect, but now we see that the problem is actually here:
You're creating a new local variable
mo
which "hides" the parametermo
.Glad we got there in the end :-)
此错误消息意味着同一方法中的某处存在另一个名为
mo
的变量。例如,这样的代码会导致此错误:您可能认为它不相关,因此您没有发布整个代码。
This error message means that there is another variable named
mo
somewhere in the same method. For example, such code would cause this error:You probably didn't think it was related, so you didn't post the whole code.
从文档
out(C# 参考)
所以应该没问题,只是你的方法语法不正确。您需要使用逗号而不是分号来分隔参数。
From the documentation
out (C# Reference)
So it should be fine, except that your method syntax is incorrect. You need to use a comma instead of a semi colon to seperate parameters.
给定您的实际代码,您无法定义 mo,因为它已经定义为输出参数
Given your actual code, you cannot define mo because it's already defined as an out parameter