你有各種答案,所以我想我會增加我的0.02美元的價值。
就我個人而言,我總是像這樣硬編碼固定列表(與郵編一樣)。這就是說,當我處於你的位置時,我會一直優化可讀性。即當你忘記了這個項目並且需要進行一些維護時,6個月內什麼纔有意義?
如果我有一個數據庫,做到這一點:
public class Country
{
public string Name { get; set; }
public Country[] BorderingCountries { get; set; }
public Country(iDB db, string name)
{
BorderingCountries = db.BorderingCountriesGet(name);
}
}
單元測試:
public UnitTest1()
{
iDB db = new DB();
Country c = new Country(db, "Spain");
Assert.AreEqual(2, c.BorderingCountries.Count());
Assert.AreEqual(1, c.BorderingCountries.Count(b => b.Name == "France"));
Assert.AreEqual(1, c.BorderingCountries.Count(b => b.Name == "Portugal"));
}
糟糕!你可能要填充整個列表(不是一次一個!) DB:
static void Main(string[] args)
{
Countries countries = new Countries(new DB());
}
public class Countries
{
public List<Country> Items { get; set; }
public Countries(iDB db)
{
tblCountry[] countries = db.BorderingCountries();
Items = new List<Country>();
Country country = null;
foreach (var c in countries)
{
if (country == null || country.Name != c.Name)
{
country = new Country(c.Name);
Items.Add(country);
}
country.BorderingCountries.Add(new Country(c.BorderingCountry));
}
}
}
public class Country
{
public string Name { get; set; }
public List<Country> BorderingCountries { get; set; }
public Country(string name)
{
this.Name = name;
BorderingCountries = new List<Country>();
}
}
public interface iDB
{
tblCountry[] BorderingCountries();
}
public class DB : iDB
{
public tblCountry[] BorderingCountries()
{
using (DataClassesDataContext dc = new DataClassesDataContext())
{
return dc.tblCountries.ToArray();
}
}
}
如果我硬編碼:
public class Countries
{
public List<Country> Items { get; set; }
public Countries()
{
Items = new List<Country>();
Items.Add(new Country { Name = "Spain", BorderingCountries = new string[] { "France", "Portugal" }});
Items.Add(new Country { Name = "France", BorderingCountries = new string[] {"Spain","Belgium"});
}
}
「它不會改變非常頻繁」 - 曾經訪問過巴爾幹地區? – 2010-05-25 08:38:33
的確,但我會認爲這些變化「不經常發生」。 – UpTheCreek 2010-05-25 08:59:17