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

最短的方法是将其重写为一行,但这不是最有效的:

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 的引用,并在您的使用中包括 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 回答