C# 检查常量中是否存在值
我已经这样声明了我的 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");
}
I have declared my c# application constant this way:
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";
}
}
My validation function:
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
}
During runtime, I will like pass in the user inputted value and the struct to check if the value exist in the struct. The struct can be profession and gender. How can I achieve it?
Example:
if(!isWithinAllowedSelection(strInput,Constant.profession)){
response.write("invalid profession");
}
if(!isWithinAllowedSelection(strInput,Constant.gender)){
response.write("invalid gender");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想使用 枚举,而不是结构与常数。
枚举为您提供了很多可能性,使用其字符串值将其保存到数据库等并不难。
现在:
通过值的名称检查
Profession
中值的存在:获取值将枚举作为字符串:
如果您确实无法避免使用带有空格或其他特殊字符的值名称,则可以使用
DescriptionAttribute
:现在,从
Profession
value 您可以使用此代码(此处作为扩展方法实现):此方法获取属性中定义的描述,如果没有,则返回值名称。用法:
You probably want to use enums, not structs with constants.
Enums gives you a lot of possibilities, it is not so hard to use its string values to save it to the database etc.
And now:
To check existence of value in
Profession
by value's name:To get value of an enum as a string:
If you really can't avoid using value names with whitespaces or other special characters, you can use
DescriptionAttribute
:And now, to get description from
Profession
value you can use this code (implemented here as an extension method):This method fetches description defined in attribute and if there's none, returns value name. Usage: