1

なぜこれが私にエラーを与えているのか混乱しました私のコードは正しいと思います

XElement outer = new XElement("Main");
XElement xsets;
XElement xsubsets;
foreach (DataRow nav_sets in GetNavigationSets().Rows)
{
    if (nav_sets["parent_id"].ToString() == null)
    {
        xsets = new XElement("Menu", nav_sets["name"].ToString());
    }
    else
    {
        if (int.Parse(nav_sets["id"].ToString()) == int.Parse(nav_sets["parent_id"].ToString()))
        {
            xsubsets = new XElement("SubMenu", nav_sets["name"].ToString());
            foreach (DataRow nav_menus in GetMenusInNavigationSetByNavigation(int.Parse(nav_sets["id"].ToString())).Rows)
            {
                foreach (DataRow menus in GetMenuById(int.Parse(nav_menus["menu_id"].ToString())).Rows)
                {
                    xsubsets.Add(new XElement("MenuItem", menus["name"].ToString()));
                }
            }
        }
        xsets.Add(xsubsets);
    }
    outer.Add(xsets);
}
outer.Save("main.xml");
cn.Close();

エラー部分はこのコード行に表示されますxsets.Add(xsubsets);

エラー:

エラー1未割り当てのローカル変数'xsets'の
使用エラー2未割り当てのローカル変数'xsubsets'の使用

どうすればこのエラーを取り除くことができるのか混乱しました。

4

2 に答える 2

2

から変更します

XElement xsets;
XElement xsubsets;

XElement xsets = null;
XElement xsubsets = null;
于 2013-02-09T00:41:59.133 に答える
1

The problem you are facing is that the compiler can't tell at compile time that the first case of the if statement is taken before the second is. Likewise in the second case, it doesn't know that before xsubsets is used, that the if statement will evaluate to true and create it. While you may know this because of the format of the expected input, the compiler can't and gives you the error about the use of an unassigned variable. By giving the variables an initial value (even null), you give them a value and the compiler is satisfied that you know what you're doing and haven't made a mistake. Of course, if you do set them to null and then try to reference properties on them before they are used, you'll get a runtime exception but it isn't the compiler's job to worry about that if you've made sure that you satisfy its criteria.

Solve your compiler warnings by assigning an initial value of null. My preference would be to go beyond that and check for null values before using them so that you can throw an exception with a more meaningful error message and log the exception condition.

于 2013-02-09T00:55:21.227 に答える