更好的方法来处理下面的代码

时间:2012-07-13 11:13:38

标签: c# asp.net

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;
}

我不想硬编码上面的值,我该怎么处理呢

5 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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);
}

答案 2 :(得分: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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

尽可能避免代码中的硬编码字符串是一种很好的做法。试试这个 -

public enum Country
{
    AF, BD, CA, IN, IR, RO, AN, CY, IL, PH
}  

......然后,

foreach (string name in Enum.GetNames(typeof(Country)))
{
    //ToDo
}