-2

我的目标:用户将选择“以换行符分隔的设备名称”列表,我的代码可以正常工作。当我尝试遍历列表并将它们输入到“设备”类型的新列表中时,就会出现问题

class Appliance{
  public string name;
  public string Firmware;
  public stirng cpu_10sec;
  public string mem;
}

这是我尝试构建“DatapowerList”的代码

string f = txt_ListofAppliances.Text;
List<Appliance> DatapowerList = new List<Appliance>();

using (StreamReader sr = new StreamReader(f))
{
  Appliance Datapower;
  While ((Datapower.name = sr.ReadLine()) != null)
  {
     DatapowerList.Add(Datapower);
  }
 }

我收到错误“使用未分配的局部变量‘Datapower’

如果这是一个新手问题,我深表歉意,如果您需要更多信息,请告诉我。

4

3 回答 3

0

您必须创建Appliance.

改变

Appliance Datapower;

Appliance Datapower = new Appliance();

您可以将代码简化为

string temp = default(string);
While ((temp = sr.ReadLine()) != null)
{
  DatapowerList.Add(new Appliance {name=temp});
}
于 2012-12-30T20:11:12.610 回答
0

另一种选择是使用File.ReadLines

foreach (var s in File.ReadLines(f))
{
    DatapowerList.Add(new Appliance { name = s });
}
于 2012-12-30T20:34:33.240 回答
-1

您有几个选择供您选择。在您提供的示例中,您必须先创建设备实例,Datapower然后才能为其中一个字段分配值:

using (StreamReader sr = new StreamReader(f))
{
    Appliance Datapower = new Appliance(); //Notice the "= new Appliance()" on this line.
    while ((Datapower.name = sr.ReadLine()) != null)
    {
        DatapowerList.Add(Datapower);
    }
}

作为我个人的偏好,我不喜欢在 while/if/etc 中分配值。陈述。对我来说,它从代码中带走了一小层可读性。我会做类似以下的事情:

using (StreamReader sr = new StreamReader(f))
{
    while (true)
    {
        string s = sr.ReadLine();
        if (s != null)
        {
            //If the line that was read isn't null, add a new instance of Appliance
            // to the list. You can assign the "name" field a value when you create
            // the instance by using the following format: "new Object() { variable = value }
            DatapowerList.Add(new Appliance() { name = s });
        }
        else
            break;
    }
}
于 2012-12-30T20:14:36.433 回答