0

我正在设置一个看起来像这样的项目列表。

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(new BankInfo { 所以我可以只做 $ITEM (就像 C++ 中的宏)?

4

1 回答 1

0

我了解您的意思是处理所有属性分配的函数:

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 文件中,用逗号分隔。如果您提供有关确切输入格式的更多信息,我可以相应地更新代码。

于 2013-07-07T09:38:14.747 回答