你的問題是「你知道更多的清潔解決方案」。 嗯...我的回答是: 我想你認爲每個國家的所有3letterCode都是由國家的前3個字母(如SPAin => SPA
)等創建的。該方法的錯誤,看看這裏: http://www.worldatlas.com/aatlas/ctycodes.htm
返回代碼:
public class CountriesFactory
{
private static List<Country> _countries = new List<Country>()
{
new Country("Spain", "Spa"),
new Country("Germany", "Ger")
}
public static Country GetCountryByName(string countryName)
{
return _countries.Where(p => p.CountryName == countryName).FirstOrDefault() ?? Country.NONE;
}
}
public class Country
{
public string CountryName { get; private set; }
public string ThreeLetterCode { get; private set; }
public const Country NONE = new Country("", "");
public Country (string countryName, string threeLetterCode)
{
this.CountryName = countryName;
this.ThreeLetterCode = threeLetterCode;
}
}
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public Country Country { get; set; }
public override string ToString()
{
return string.Format("{0} {1}. ({2})", Name, Surname[0].ToString(), Country.ThreeLetterCode);
}
}
有你應該添加一些條件,但現在並不重要。
使用代碼:
Person person = new Person()
{
Name = "Endi",
Surname = "Marrei",
Country = CountriesFactory.GetCountryByName("Spain")
}
Console.WriteLine(person.ToString());
你的榜樣:
var firstString = "Endi Marrei";
var SecondString = "Spain";
var person = new Person()
{
Name = firstString.Split(' ')[0].ToString(),
Surname = firstString.Split(' ')[1].ToString(),
Country = CountriesFactory.GetCountryByName(SecondString)
}
我認爲我的做法將在未來更加有用。
來源
2016-06-19 15:26:46
W92
「即使我的方式工作,」 - 是什麼呢?當你的問題要求「Marrei E.(Spa)」時,你得到了「Marrei E.(???)」,你不是嗎? – hvd
我已經在Visual Studio中運行我的代碼,它可以工作。嘗試運行它 – Yoseph