测试对象是否为枚举


Answers:


203

问题是答案。:)

bool isEnum = theObject is Enum;

13
爱它!甚至更接近问题:如果(theObject是Enum){...}
Peter Lillevold 2010年

5
这甚至不是我来这里的目的,我想给您一点。太...干净了... <嗅>,是个漂亮的男人TT
Lukas 2012年

12
/ *测试* /如果(anObject是/ * an * /枚举){}
汤姆·佛伯

bool isEnum = theObject.GetType()。IsEnum; 更好,是Enum并不总是返回true
克里斯·胡

67

如果您有Type,请使用Type.IsEnum属性,例如:

bool isEnum = theObject.GetType().IsEnum;

2
这对我有用。我不知道如何使接受的答案在VB.NET中起作用。
Shea Daniels

4
我实际上需要知道如何检查是否为Type枚举类型。+1
弥敦道


0

对于泛型类型参数,可以对参数进行约束而不是对其进行测试:

where T : Enum
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.