在访问c#之前,可能未初始化局部变量

时间:2016-07-03 02:04:31

标签: c#

所以我试着解决这个问题。我知道一个事实,这将在我调用它之前初始化,但c#我不知道这个。 我不能做xUser user = new xUser; 一个解决方法我正在考虑使用List并将值存储在列表中,然后在while循环之后创建xuser但它看起来非常混乱。我真的想学习如何避免这种错误。

        noUSer iuser = new noUSer();
        xUser user;
        string sql = "select * from accounts where id='" +id +"'";
        SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
        SQLiteDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {

            iuser.user_name = reader["login"].ToString();
            iuser.password = reader["password"].ToString();
            iuser.cookie_file = @"c:\cookies";

            user = iusers.create(iguser);


        }



        m_dbConnection.Close();
        if (tab_mode.SelectedTab.Text == "User")
        {
           dothiscall(user); //Error on "user" local variable might be not initialized before accessing

        }

3 个答案:

答案 0 :(得分:4)

您应该将变量初始化为null,但是,请注意,如果while循环中的代码不执行,它将保持为null。

答案 1 :(得分:0)

更好的方法是创建一个列表iusers并在while循环中添加新的iuser。你的user正在添加无法找到的iguser。它应该是iuser

   xUser user = new xUser();
   string sql = "select * from accounts where id='" +id +"'";
   SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
   SQLiteDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        noUSer iuser = new noUSer();
        iuser.user_name = reader["login"].ToString();
        iuser.password = reader["password"].ToString();
        iuser.cookie_file = @"c:\cookies";

        user = iusers.Add(iuser);

    }

答案 2 :(得分:0)

当你这样做时:

xUser user;

你只是在创建一个指针。意思是如果你之后有一个类型为xUser的对象,并且想要一个指向它的指针,你可以这样做,例如:

user =(xUser)DataGridView1.Rows[0].cells[myxUserObjectInCell.index].Value;

这样,对用户进行更改将更改网格中的对象。 但是,如果您计划创建xUser类型的对象,则需要执行以下操作:

xUser user = new xUser();

新关键字使其初始化。

相关问题