解析字符串并将每个名称(以换行符分隔)读入列表对象
本文关键字:分隔 换行符 对象 列表 字符串 字符 串并 | 更新日期: 2023-09-27 17:50:23
我的目标:用户将选择一个"以换行符分隔的设备名称"的列表,我使这段代码正常工作。当我尝试遍历列表并将它们输入到类型为"Appliance"
的新列表中时,问题就出现了。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'
如果这是一个新手问题,我很抱歉,如果你需要更多的信息,请告诉我。
您必须创建Appliance
的实例。
Appliance Datapower;
Appliance Datapower = new Appliance();
您可以将代码简化为
string temp = default(string);
While ((temp = sr.ReadLine()) != null)
{
DatapowerList.Add(new Appliance {name=temp});
}
另一个选项是使用File。readline:
foreach (var s in File.ReadLines(f))
{
DatapowerList.Add(new Appliance { name = s });
}
您有几个选项可供选择。在您提供的示例中,必须先创建Appliance 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;
}
}