C# 错误:必须在控制离开当前方法之前分配 Out 参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11738042/
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
Error : The Out Parameter must be assigned before control leaves the current method
提问by fdgfdgs dfg
While sending back parameters getting this error
发回参数时出现此错误
Error : The Out Parameter must be assigned before control leaves the current method
错误:必须在控制离开当前方法之前分配 Out 参数
Code is
代码是
public void GetPapers(string web, out int Id1, out int Id2)
{
SqlConnection conn = new SqlConnection(ConnectionString());
conn.Open();
SqlCommand cmd = new SqlCommand("GetPapers", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@URL", String(web)));
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
Id1 = (int)rdr["ID1"];
Id2 = (int)rdr["ID2"];
}
rdr.Close();
}
calling it as
称其为
GetPapers(web, out Id1, out Id2);
Related to this question
与此问题相关
采纳答案by Habib
You are assigning Id1and Id2inside an if statement and compiler can't determine if it will be assigned a value at run time, thus the error.
您正在if 语句中分配Id1和Id2内部,编译器无法确定是否会在运行时为其分配一个值,因此会出现错误。
You could assign them some default value before the if statement. Something like.
您可以在 if 语句之前为它们分配一些默认值。就像是。
Id1 = 0;
Id2 = 0;
if (rdr.Read())
{
Id1 = (int)rdr["ID1"];
Id2 = (int)rdr["ID2"];
}
or specify some default values in elsepart of your condition.
或在else您的部分条件中指定一些默认值。
An outtype parameter must be assigned some value, before the control leaves the functions. In your case, compiler can't determine whether your variables will be assigned or not, because it is being assigned inside an ifstatement.
一个out类型参数必须分配一定的价值,控制叶片的功能之前。在您的情况下,编译器无法确定您的变量是否会被分配,因为它是在if语句中分配的。
参见:5.3 明确赋值
At a given location in the executable code of a function member, a variable is said to be definitely assigned if the compiler can prove, by static flow analysis,that the variable has been automatically initialized or has been the target of at least one assignment.
在函数成员的可执行代码中的给定位置,如果编译器可以通过静态流分析证明该变量已自动初始化或已成为至少一次赋值的目标,则称该变量已被明确赋值。
回答by Dhanasekar
You need to initialise those variables ;
您需要初始化这些变量;
it must hold some value before returned from the Getpapers() method
它必须在从 Getpapers() 方法返回之前保存一些值

