首页 文章

C#未分配的局部变量错误

提问于
浏览
2

我是C#的新手 . 我试图编译以下程序,但最后会抛出一个错误:我知道我犯了一个愚蠢的错误 . 任何帮助将非常感激:

static void Main(string [] args){

IntPtr hCannedMessages = CannedMessagesInit();

        using (StreamReader sr = new StreamReader(CANNED_MESSAGE_FILE))
        {
            String line, sub;
            all_integer_IDs[] myobjarray;// = new all_integer_IDs[10];
            for (int c = 0; c < 10; c++)
            {
                myobjarray[c] = new all_integer_IDs();

            }
                line = sr.ReadLine();
                Console.WriteLine(line);

                if (line.Length > 15)
                {
                     sub = line.Remove(line.IndexOf(' ', 2));
                     Console.WriteLine("{0} \n",sub);

    myobjarray[0].setvalues((int)sub[2], (int)sub[3], (int)sub[4], (int)sub[5]);

Console.WriteLine(“{0},{1},{2},{3}”,myobjarray [0] .m_messageID,myobjarray [0] .m_messagetype,myobjarray [0] .m_classID,myobjarray [0] .m_categoryID) ; }

Console.Read();
            sr.Close();
        }

    }
}

}

该类位于同一项目的Class1.cs文件中,如下所示:

公共类all_integer_IDs {

public all_integer_IDs() 
    {

        setvalues(0, 0, 0, 0);

    }

    ~all_integer_IDs()
    {
    }

    public void setvalues (int messageID, int messagetype, int classID, int categoryID)
    {
        this.m_messageID = messageID;
        this.m_messagetype = messagetype;
        this.m_classID = classID;
        this.m_categoryID = categoryID;
    }

     public int m_messageID;
     public int m_messagetype;
     public int m_classID;
     public int m_categoryID;

}

错误如下:在第55行使用未分配的局部变量'myobjarray',复制并粘贴在下面:myobjarray [c] = new all_integer_IDs();

谢谢,Viren

4 回答

  • 0

    你永远不会初始化myobjarray . 你宣布myobjarray,但你没有为它分配任何记忆;如:你没有初始化变量 . 你确实初始化了数组的元素(还有另一个数组),但你没有为myobjarray本身重新保存任何内存 .
    (初始化被注释掉了)

  • 2

    您尚未为myObjarray分配空间 . 你需要分配它

    使用:

    all_integer_IDs[] myobjarray = new all_integer_IDs[10];
    for (int c = 0; c < 10; c++)
    {
        myobjarray[c] = new all_integer_IDs();
    }
    

    在第55行 .

    请使用PascalCase作为类名(在您的情况下,AllIntegerIDs) . 其他开发人员会感谢你

    --EDIT,我的坏 . 纠正了调用它的方式 . 请尝试以下方法

  • 1

    看起来你需要在实例化时声明数组myobjarray的大小和类型 . 事实上,看起来你已经有了这个代码,你只需要删除注释符号 .

    all_integer_IDs[] myobjarray = new all_integer_IDs[10]();
    
  • 0

    你从来没有实例化你的数组,似乎你注释掉了那个部分 .

    如果需要可变长度数组,请尝试使用列表<> .

相关问题