如何在公共方法中验证枚举参数? [英] How do I validate an enum parameter on a public method?

查看:196
本文介绍了如何在公共方法中验证枚举参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static List&Enum>值(this Enum theEnum)
{
return Enum.GetValues(theEnum.GetType())。Cast&Enum>()ToList();
}

我正在收到代码分析违规:


CA1062验证公共方法的参数

在外部可见的
方法'EnumExtensions.Values(此枚举)'中,验证参数
'theEnum'在使用它之前。


为什么会这样?如何验证参数?我无法检查null,因为枚举是不可为空的值类型。是否还有其他支票应该在这里发生?

解决方案


我无法检查因为枚举是不可为空的值类型。


任何特定的枚举是值类型,但 枚举 本身不是。 (就像 ValueType 不是一个值类型...每个类型派生自 ValueType 除了枚举 是一个值类型。)



换句话说,我可以写:

 枚举foo = null; 
var bang = foo.GetValues();

这将编译,然后在执行时失败,使用 NullReferenceException

鉴于您忽略除了获取其类型之外的值,我实际上建议删除它, 接受一个键入 ,使其在所需的枚举类型中是通用的。但是如果你想保留当前的签名,你只需要:

  if(theEnum == null)
{
throw new ArgumentNullException();
}

您可能还想查看我的无限旋律项目,为枚举提供了一系列帮助方法,通常通过IL操纵限制枚举类型。


I have this extension method for an Enum:

public static List<Enum> Values(this Enum theEnum)
{
    return Enum.GetValues(theEnum.GetType()).Cast<Enum>().ToList();
}

I'm getting a code analysis violation:

CA1062 Validate arguments of public methods
In externally visible method 'EnumExtensions.Values(this Enum)', validate parameter 'theEnum' before using it.

Why is that happening? How can I validate the parameter? I can't check for null because an enum is a non-nullable value type. Is there some other check that is supposed to be occurring here?

解决方案

I can't check for null because an enum is a non-nullable value type.

Any particular enum is a value type, but Enum itself isn't. (Just like ValueType isn't a value type either... every type derived from ValueType except Enum is a value type.)

In other words, I could write:

Enum foo = null;
var bang = foo.GetValues();

That would compile and then fail at execution time with a NullReferenceException.

Given that you ignore the value except to get its type, I'd actually suggest removing it and either accepting a Type or making it generic in the type of enum you want. But if you want to keep the current signature, you just need:

if (theEnum == null)
{
    throw new ArgumentNullException();
}

You might also want to look at my Unconstrained Melody project which provides a bunch of helper methods for enums, generically constrained to enum types via IL manipulation.

这篇关于如何在公共方法中验证枚举参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆