C#检查值存在于常量中

时间:2010-10-21 10:06:46

标签: asp.net-2.0 c#-2.0

我已经通过这种方式声明了我的c#应用程序:

public class Constant
 public struct profession
 {
  public const string STUDENT = "Student";
  public const string WORKING_PROFESSIONAL = "Working Professional";
  public const string OTHERS = "Others";
 }

 public struct gender
 {
  public const string MALE = "M";
  public const string FEMALE = "F";  
 }
}

我的验证功能:

public static bool isWithinAllowedSelection(string strValueToCheck, object constantClass)
{

    //convert object to struct

    //loop thru all const in struct
            //if strValueToCheck matches any of the value in struct, return true
    //end of loop

    //return false
}

在运行时,我想传入用户输入的值和结构来检查结构中是否存在该值。结构可以是职业和性别。我怎样才能实现它?

示例:

if(!isWithinAllowedSelection(strInput,Constant.profession)){
    response.write("invalid profession");
}

if(!isWithinAllowedSelection(strInput,Constant.gender)){
    response.write("invalid gender");
}

1 个答案:

答案 0 :(得分:4)

您可能希望使用enums,而不是使用常量结构。


Enums为您提供了很多可能性,使用其字符串值将其保存到数据库等并不是那么难。

public enum Profession
{
  Student,
  WorkingProfessional,
  Others
}

现在:

通过值的名称检查Profession中是否存在值:

var result = Enum.IsDefined(typeof(Profession), "Retired"));
// result == false

要将枚举值作为字符串获取:

var result = Enum.GetName(typeof(Profession), Profession.Student));
// result == "Student"

如果你真的无法避免使用带有空格或其他特殊字符的值名称,可以使用DescriptionAttribute

public enum Profession
{
  Student,
  [Description("Working Professional")] WorkingProfessional,
  [Description("All others...")] Others
}

现在,要从Profession值获取描述,您可以使用此代码(在此处作为扩展方法实现):

public static string Description(this Enum e)
{
    var members = e.GetType().GetMember(e.ToString());

    if (members != null && members.Length != 0)
    {
        var attrs = members.First()
            .GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attrs != null && attrs.Length != 0)
            return ((DescriptionAttribute) attrs.First()).Description;
    }

    return e.ToString();
}

此方法获取在属性中定义的描述,如果没有,则返回值名称。用法:

var e = Profession.WorkingProfessional;
var result = e.Description();
// result == "Working Professional";