2013-08-01 65 views
-1

我的程序找到您的IP地址與國家。 當你從德國,它會顯示DE 當你在美國會顯示美國 等C#字符串分配

現在我的問題是,如何全自動也許從胡轉串匈牙利。 我應該創建一個項目表還是這樣的?

Screenshot

在那裏,你看,我發現了從網站http://api.hostip.info/country.php 你看到的獲取IP按鈕國家之上的國家信息:DE,我想改變這種全自動德國

+2

可能是一本字典。完整列表是[here](http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm) –

回答

1

你可以創建一個字典並將該鍵設置爲您的返回結果,並將該值設置爲所需的國家/地區名稱。看看這裏的基本概述:Tutorial

1

下面是解決此問題的兩種選擇:

  • 建立一個Dictionary<Country, string>
  • 使用Country枚舉,並用Description屬性

裝飾它建立一個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(); 
} 

現在,您可以通過靜態ConvertCountry方法使用Dictionary<Country, string>,就像這樣:

var myCountry = ConvertCountry(Country.UnitedStates)); 

使用Country枚舉和裝飾它與Description屬性,像這樣:

enum Country 
{ 
    [Description("US")] 
    UnitedStates, 
    [Description("DE")] 
    Germany, 
    [Description("HU")] 
    Hungary 
} 

現在你可以使用此方法獲得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(); 
    } 

使用上述方法,像這樣:

var myCountryDescription = GetDescription(Country.UnitedStates); 
+0

你能給我一個liittllee的例子嗎? :) –

+0

+1個不錯的答案,@DiarDo複製代碼,並以其優雅的方式走,它更簡單會失去優雅。 –

+0

難道他們不想要與此相反嗎?他們想把「美國」解決爲「美國」。 –

1

您可以創建一個對象關係的短期和使用該 table長國名。

這也是另一個帖子,回答this post