2013-07-07 20 views
0

我正在設置一個類似這樣的項目列表。基於文本文件定義項目(C#)

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#),以讓這個像$項的符號變成all_branches.Add(新BankInfo {所以我只能做$項目(如在C++)宏?

+0

如何從文本或XML文件中讀取所有這些數據,然後編寫一個函數來完成所有這些操作。 – Pankaj

回答

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 
{ 
} 

在上面的例子中,我假設所有的輸入AR e在TXT文件中,用逗號分隔。如果您提供有關確切輸入格式的更多信息,我可以相應地更新代碼。

+0

啊!愚蠢的我忘記了,當然你可以簡單地從文本文件中讀取信息。謝謝您的幫助 :)。 – Coat

+0

沒問題。這是這個網站的目的:) – varocarbas