验证枚举值 [英] Validate Enum Values
本文介绍了验证枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要验证一个整数知道是否是一个有效的枚举值。
I need to validate an integer to know if is a valid enum value.
什么是C#做到这一点的最好方法是什么?
What is the best way to do this in C#?
推荐答案
您会爱上这些民间谁假设数据不仅始终来自于一个用户界面,但你的控制范围之内的UI!
You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!
IsDefined
适用于大多数情况下,你可以使用启动:
IsDefined
is fine for most scenarios, you could start with:
public static bool TryParseEnum<TEnum>(this int enumValue, out TEnum retVal)
{
retVal = default(TEnum);
bool success = Enum.IsDefined(typeof(TEnum), enumValue);
if (success)
{
retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);
}
return success;
}
(显然刚落'这个'如果你不认为这是一个合适的INT扩展)
(Obviously just drop the ‘this’ if you don’t think it’s a suitable int extension)
这篇关于验证枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文