c# - 错误 : The Out Parameter must be assigned before control leaves the current method

标签 c# compiler-errors .net-2.0

发送回参数时出现此错误

Error : The Out Parameter must be assigned before control leaves the current method

代码是

 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();
    }

称其为

GetPapers(web, out Id1, out Id2);

与此问题相关

Related question

最佳答案

您在 if 语句中分配 Id1Id2,编译器无法确定它是否会在运行时分配一个值,因此会出现错误。

您可以在 if 语句之前为它们分配一些默认值。就像是。

Id1 = 0;
Id2 = 0;

if (rdr.Read())
{
    Id1 = (int)rdr["ID1"];
    Id2 = (int)rdr["ID2"];
}

或在条件的 else 部分指定一些默认值。

在控件离开函数之前,必须为 out 类型参数分配一些值。在您的情况下,编译器无法确定您的变量是否会被分配,因为它是在 if 语句中分配的。

参见:5.3 Definite assignment

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.

关于c# - 错误 : The Out Parameter must be assigned before control leaves the current method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11738042/

相关文章:

c# - 从 PCM 数据中获取音频信息

c# - 在word文档的页脚中添加从第n页开始的页码

c# - 想要在 gridview 的一列中获取相同字符串值的总数

c# - 不实现 System.IComparable.CompareTo(object)

c# - Socket.Send 缓冲区大小是否有限制?

c# - 如何从字符串中删除所有空格?

ios:<错误>:CGAffineTransformInvert:奇异矩阵

c++ - STL 嵌套容器取消引用错误

wcf - 在 .net 2 中使用 WCF

C#对接控制库