1
private bool CheckMemberCountry(string country)
{
    string[] countries = new string[] { "AF", "BD", "CA", "IN", "IR", "RO", "AN", "CY", "IL", "PH" };
    foreach (string memberCountry in countries)
    {
        if (memberCountry.Equals(country))
        {
            return true;
        }
    }

    return false;
}

上記のように値をハードコーディングしたくないのですが、どうすればそれを処理できますか

4

4 に答える 4

4

最短の方法は1行で書き直すことですが、最も効率的ではありません。

return (new string[] { "AF", "BD", "CA", "IN", "IR", "RO", "AN", "CY", "IL", "PH" })
    .Contains(country);

配列を静的読み取り専用変数にして、関数で使用する必要があります。

private static readonly string[] AllCountries = new string[] {
    "AF", "BD", "CA", "IN", "IR", "RO", "AN", "CY", "IL", "PH"
};

private bool CheckMemberCountry(string country) {
    return AllCountries.Contains(country);
}
于 2012-07-13T11:15:35.733 に答える
3

使用String.Contains():

static string[] Countries = new string[] { "AF", "BD", "CA", "IN", "IR", "RO", "AN", "CY", "IL", "PH" };    

private bool CheckMemberCountry(string country)
{       
   return Countries.Contains(country);
}
于 2012-07-13T11:15:07.600 に答える
1

国のリストが変更される可能性が低い場合は、次のようにすることができます。

// note: sorted alphabetically
private static readonly string[] countries =  new string[] { 
  "AF", "AN", "BD", "CA", "CY", "IL",
  "IN", "IR", "PH", "RO" }; 

private bool CheckMemberCountry(string country)
{
    return Array.BinarySearch<string>(countries, country) >= 0;
}

国が変更された場合は、それらを構成ファイルに入れることができます。App.config ファイルは次のようになります。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
     <add key="countries" value="AF,BD,CA,IN,IR,RO,AN,CY,IL,PH"/>
  </appSettings>
</configuration>

上記のコードでは、次の行を置き換えることができます。

private static readonly string[] countries =  new string[] {
       "AF", "AN", "BD", "CA", "CY", "IL",
       "IN", "IR", "PH", "RO" };

(System.Configuration.dll への参照を含め、Usings に System.Configuration を含めます):

using System.Configuration;

// ...

private static readonly string[] countries =  ConfigurationManager
    .AppSettings["countries"] // configuration setting with key "countries"
    .Split(',') // split comma-delimited values
    .Select(a=>a.Trim()) // trim each value (remove whitespace)
    .OrderBy(a=>a) // sort list (for binary search)
    .ToArray(); // convert to array
于 2012-07-13T11:42:45.303 に答える
0
private bool CheckMemberCountry(string country)
{
   return new string[] { "AF", "BD", "CA", "IN", "IR", "RO", "AN", "CY", "IL", "PH" }.Contains(country);
}
于 2012-07-13T11:24:37.620 に答える