How do I validate an enum parameter on a public method?

让人想犯罪 __ 提交于 2019-12-11 17:26:20

问题


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?


回答1:


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.




回答2:


The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.

It is used just for declare another enums. In any case, the input should be your declaration.

public enum theEnum { 
  enum1,
  enum2
}

public void ShowEnum(theEnum e) 
{
   System.Console.WriteLine(e.GetType());        
}


来源:https://stackoverflow.com/questions/23808427/how-do-i-validate-an-enum-parameter-on-a-public-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!