错误:必须在控制离开当前方法之前分配 Out 参数 [英] Error : The Out Parameter must be assigned before control leaves the current method

查看:35
本文介绍了错误:必须在控制离开当前方法之前分配 Out 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发回参数时出现此错误

错误:必须在控制离开之前分配输出参数当前方法

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

关于这个问题

相关问题

推荐答案

您在 if 语句中分配 Id1Id2 并且编译器无法确定它是否会在运行时被赋值,因此错误.

You are assigning Id1 and Id2 inside an if statement and compiler can't determine if it will be assigned a value at run time, thus the error.

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

You could assign them some default value before the if statement. Something like.

Id1 = 0;
Id2 = 0;

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

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

or specify some default values in else part of your condition.

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

An out type 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 if statement.

参见: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.

这篇关于错误:必须在控制离开当前方法之前分配 Out 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆