C# 必须在控制离开当前方法之前分配 out 参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18828133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The out parameter must be assigned to before control leaves the current method
提问by Dana Yeger
private void getDetails(out IPAddress ipAddress, out int port)
{
IPAddress Ip;
int Port;
try
{
Ip = IPAddress.Parse(textboxIp.Text);
Port = int.Parse(textboxPort.Text);
}
catch (Exception ex)
{
IPAddress Ip null;
int Port = -1;
MessageBox.Show(ex.Message);
}
}
Why i got this compiler error ? my parameters assigned to value in both cases
为什么我得到这个编译器错误?我的参数在两种情况下都分配给 value
采纳答案by matt
You're not assigning any values to the parameters passed into the method - ipAddress
and port
. Instead of declaring new Ip
and Port
variables, just assign the values to the parameters you've passed in:
您没有为传递给方法的参数分配任何值 -ipAddress
和port
. 无需声明 newIp
和Port
变量,只需将值分配给您传入的参数:
private void getDetails(out IPAddress ipAddress, out int port)
{
try
{
ipAddress = IPAddress.Parse(textboxIp.Text);
port = int.Parse(textboxPort.Text);
}
catch (Exception ex)
{
ipAddress = null;
port = -1;
MessageBox.Show(ex.Message);
}
}
EDIT:For other developers, if using "out", you must allow the variable the ability to be set at all points in the function - including "if" statements, and the "catch", like here, just like it was being returned, or it will give the error this guy got.
编辑:对于其他开发人员,如果使用“out”,则必须允许在函数的所有点设置变量的能力 - 包括“if”语句和“catch”,就像这里一样,就像它被返回一样,否则它会给出这个家伙得到的错误。
回答by meilke
You are not assigning values to both of the out
variables. You are justassigning values to the ones you created inside the method.
您没有为这两个out
变量赋值。您只是将值分配给您在方法中创建的值。
回答by Mark Sherretta
No, you have created another variable - int Port
, that is not the same as out int port
. You are not assigning a value to the actual out parameter. Same goes for the ipAddress
out parameter.
不,您创建了另一个变量 - int Port
,它与out int port
. 您没有为实际的输出参数分配值。这同样适用于ipAddress
输出参数。
回答by Dan Puzey
Quite obviously, you don't assign any value to your out
parameters ipAddress
and port
at any point in the method.
很显然,你不分配给您的任何值out
的参数ipAddress
,并port
在方法中的任一点。