【问题标题】:Defining Items Based on Text File (C#)基于文本文件定义项目 (C#)
【发布时间】:2013-07-07 09:10:50
【问题描述】:

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

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++ 中的宏)?

【问题讨论】:

  • 如何从文本或 XML 文件中读取所有这些数据,然后编写一个函数来完成所有这些操作。

标签: c# file text macros


【解决方案1】:

我明白你的意思是一个处理所有属性分配的函数:

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

【讨论】:

  • 啊!愚蠢的我,我忘了你当然可以简单地从文本文件中读取信息。感谢您的帮助:)。
  • 没问题。这就是这个网站的用途:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
相关资源
最近更新 更多