[英]C# string assign
My programm locates your IP Adress with country. 我的程序可以找到您所在国家的IP地址。 when you are from germany, it will display DE when you are in USA it will display US etc.
当您来自德国时,在美国时会显示DE,而在美国时将显示DE。
Now my question is how to turn automaticly the string maybe from HU to Hungary. 现在我的问题是如何自动将弦从HU转到匈牙利。 Should i create an itemlist or sth like that?
我应该创建类似的项目清单吗?
There you see, I'm getting the country information from a website http://api.hostip.info/country.php You see above the Get IP button Country: DE and i want to change this automaticly in Germany 在那里,您看到了,我正在从网站http://api.hostip.info/country.php获取国家信息。在“获取IP”按钮上方看到“国家:DE”,我想在德国自动进行更改
Here are two options for solving this issue: 这是解决此问题的两个选项:
Dictionary<Country, string>
Dictionary<Country, string>
Country
enumeration and decorate it with a Description
attribute Country
枚举并用Description
属性进行修饰 Build a Dictionary<Country, string>
, like this: 建立一个
Dictionary<Country, string>
,像这样:
enum Country
{
UnitedStates,
Germany,
Hungary
}
Dictionary<Country, string> CountryNames = new Dictionary<Country, string>
{
{ Country.UnitedStates, "US" },
{ Country.Germany, "DE" }
{ Country.Hungary, "HU" }
};
static string ConvertCountry(Country country)
{
string name;
return (CountryNames.TryGetValue(country, out name))
? name : country.ToString();
}
Now you can use the Dictionary<Country, string>
via the static ConvertCountry
method, like this: 现在,您可以通过静态
ConvertCountry
方法使用Dictionary<Country, string>
,如下所示:
var myCountry = ConvertCountry(Country.UnitedStates));
Use the Country
enumeration and decorate it with a Description
attribute, like this: 使用“
Country
枚举并用Description
属性对其进行修饰,如下所示:
enum Country
{
[Description("US")]
UnitedStates,
[Description("DE")]
Germany,
[Description("HU")]
Hungary
}
Now you can use this method to get a Description
attribute value, like this: 现在,您可以使用此方法来获取
Description
属性值,如下所示:
public static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return en.ToString();
}
Usage of above method, like this: 上面方法的用法,像这样:
var myCountryDescription = GetDescription(Country.UnitedStates);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.