C# 检查值是否存在于常量中

Den*_*nny 2 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";  
 }
}
Run Code Online (Sandbox Code Playgroud)

我的验证功能:

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
}
Run Code Online (Sandbox Code Playgroud)

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

例子:

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

if(!isWithinAllowedSelection(strInput,Constant.gender)){
    response.write("invalid gender");
}
Run Code Online (Sandbox Code Playgroud)

NOt*_*Dev 5

您可能想要使用enums,而不是带有常量的结构。


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

public enum Profession
{
  Student,
  WorkingProfessional,
  Others
}
Run Code Online (Sandbox Code Playgroud)

现在:

要按Profession值的名称检查值是否存在:

var result = Enum.IsDefined(typeof(Profession), "Retired"));
// result == false
Run Code Online (Sandbox Code Playgroud)

以字符串形式获取枚举值:

var result = Enum.GetName(typeof(Profession), Profession.Student));
// result == "Student"
Run Code Online (Sandbox Code Playgroud)

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

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

现在,要从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();
}
Run Code Online (Sandbox Code Playgroud)

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

var e = Profession.WorkingProfessional;
var result = e.Description();
// result == "Working Professional";
Run Code Online (Sandbox Code Playgroud)