你的问题是“你知道更多的清洁解决方案”。 嗯...我的回答是: 我想你认为每个国家的所有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