Bob*_*orn 0 c# validation enums code-analysis
我有这个Enum的扩展方法:
public static List<Enum> Values(this Enum theEnum)
{
return Enum.GetValues(theEnum.GetType()).Cast<Enum>().ToList();
}
Run Code Online (Sandbox Code Playgroud)
我收到了代码分析违规行为:
CA1062验证公共方法的参数
在外部可见方法'EnumExtensions.Values(this Enum)'中,在使用之前验证参数'theEnum'.
为什么会这样?如何验证参数?我无法检查null,因为枚举是一个不可为空的值类型.是否有其他检查应该在这里发生?
我无法检查null,因为枚举是一个不可为空的值类型.
任何特定的枚举都是值类型,但Enum本身不是.(就像ValueType不是值类型一样......从ValueType exceptEnum派生的每个类型都是值类型.)
换句话说,我可以写:
Enum foo = null;
var bang = foo.GetValues();
Run Code Online (Sandbox Code Playgroud)
那将编译然后在执行时失败NullReferenceException.
既然你忽略除获得其类型的值,其实我建议取消它,要么接受Type 或使其成为你想枚举类型通用的.但是如果你想保留当前的签名,你只需要:
if (theEnum == null)
{
throw new ArgumentNullException();
}
Run Code Online (Sandbox Code Playgroud)
您可能还想查看我的Unconstrained Melody项目,该项目为枚举提供了一堆辅助方法,通常通过IL操作约束枚举类型.