我正在设置一个项目列表,如下所示。
List<BankInfo> all_branches = new List<BankInfo>();
Equipment.set_slot = "Mail";
all_branches.Add(new BankInfo
{
name = "West Bank",
city = "San Francisco",
owner = new Person { name = "Jeff Bridges", age = 55 }
});
all_branches.Add(new BankInfo
{
name = "East Bank",
city = "Concord",
owner = new Person { name = "Upton Sinclair", age = 102 }
});从字面上看,编写成百上千个这样的代码是相当麻烦的,我更喜欢这样写
--
Name: West Bank
City: San Francisco
Owner: Jeff Bridges, 55
--
Name: East Bank
City: Concord
Owner: Upton Sinclair, 102有没有办法做到这一点呢?
至少,有没有办法(在c#中)让像$ITEM这样的符号变成all_branches.Add(新的BankInfo {这样我就可以只做$ITEM (就像C++中的宏)?)
发布于 2013-07-07 17:38:15
我理解您所指的是一个负责所有属性分配的函数:
private List<BankInfo> addToBankInfo(string name, string city, string owner_name, int owner_age, List<BankInfo> all_branches)
{
return all_branches.Add(new BankInfo { name = name, city = city, owner = new Person { name = owner_name, age = owner_age } });
}你可以调用它:
List<BankInfo> all_branches = new List<BankInfo>();
Equipment.set_slot = "Mail";
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("input_file.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if(line != null && line.Trim().Length > 0 && line.Contains(","))
{
string[] temp = line.Split(',');
if(temp.Length >= 4)
{
all_branches = addToBankInfo(temp[0], temp[1], temp[2], Convert.ToInt32(temp[3]), all_branches);
}
}
}
}
}
catch
{
}在上面的例子中,我假设所有的输入都在一个用逗号分隔的TXT文件中。如果您提供有关确切输入格式的更多信息,我可以相应地更新代码。
https://stackoverflow.com/questions/17510716
复制相似问题