简体   繁体   English

C#“使用未分配的局部变量”

[英]C# 'Use of an unassigned local variable'

I am having an issue with C# where I am getting the error 我在遇到错误的C#时遇到问题

Use of an unassigned local variable 使用未分配的局部变量

I am unsure as to why I am getting this error, as from reading other questions regarding this issue it is people having issues with declaring variables within If statements. 我不确定为什么会出现此错误,因为从阅读有关此问题的其他问题来看,人们在If语句中声明变量存在问题。

I do not know if this is a very basic error as I am new to C#, but any help would be appreciated. 我不知道这是否是一个非常基本的错误,因为我是C#的新手,但是任何帮助将不胜感激。

Here is my code: 这是我的代码:

private void remProj_Click(object sender, EventArgs e) 
{
    string[] CurrentProjects;
    for (int i = 0; i < ProjectList.Items.Count; i++) 
    {
        CurrentProjects[i] = ProjectList.Items[i].ToString();
        MessageBox.Show(CurrentProjects[i]);
    }
}

I am getting the error on this line regarding the use of 'CurrentProjects': 我在关于“ CurrentProjects”的使用的这一行上遇到错误:

CurrentProjects[i] = ProjectList.Items[i].ToString();

The error message saying that the variable CurrentProjects is not yet initialized. 错误消息指出变量CurrentProjects尚未初始化。 you you can escape from this issue by initializing the variable. 您可以通过初始化变量来避免此问题。 For this particular scenario the best option for initializing is with the ProjectList.Items.Count . 对于此特定方案,初始化的最佳选择是使用ProjectList.Items.Count So Change the declaration as like this: 因此,像这样更改声明:

 string[] CurrentProjects= new string[ProjectList.Items.Count];

您必须先将数组初始化为一个大小:

string[] CurrentProjects = new string[ProjectList.Items.Count];

I also noticed this lately that you cannot create a variable without assigning a value or something to it. 我最近也注意到这一点,如果不给变量赋值或其他东西就不能创建变量。 its an Update on c#, so basically anytime creating a variable, you must assign a value to it.. 它是c#的更新,因此基本上在任何时候创建变量,都必须为其赋值。

so 所以

string[] CurrentProjects; 

should be 应该

string[] CurrentProjects = new string[ProjectList.Items.Count];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM