简体   繁体   English

如何检查对象是否为枚举

[英]How to check if an object is an Enum

I have a SQL query builder method: 我有一个SQL查询生成器方法:

public static string PreprocessSQL(string sql, params object[] args) 

Provided that the sql parameter is "String.Format friendly", this method loops through the params and plugs them into the query string, doing whatever needs to be done based on the type of the argument - convert a null to string "NULL", surround a string with single quotes, etc. 假设sql参数为“ String.Format友好”,则此方法循环遍历参数并将其插入查询字符串中,根据参数的类型执行所需的任何操作-将null转换为字符串“ NULL”,用单引号将字符串引起来,等等。

Now the problem is with enums. 现在问题出在枚举上。 I need a logic that checks if the type of current args[i] is Enum, and if so, convert it to int. 我需要一个逻辑来检查当前args [i]的类型是否为Enum,如果是,则将其转换为int。 How to do this check? 如何检查? My first guess, for some reason, doesn't work: 由于某些原因,我的第一个猜测无效:

if(args[i].GetType() == typeof(Enum)) {
    converted.Add((int)args[i]);
}

The above condition apparently gets evaluated as false. 上述条件显然被评估为假。

My enum class is: 我的枚举类是:

public enum Priority {
    Low,
    Normal,
    High
}

If a pass a value of Priorty.Normal to this method, I figured the "value" is Normal, and the type of that value is Priority, which autmatically inherits from Enum, so I'm done. 如果将Priority.Normal的值传递给此方法,则我认为“值”是Normal,而该值的类型是Priority,这是自动从Enum继承的,所以我完成了。 Turns out it's not that simple, and from what I can tell, it looks like the type of the value Normal is actually Priority.Normal 事实并非如此简单,据我所知,看起来Normal值的类型实际上是Priority.Normal

Now I could explicitly check for all the enums I'm using in my project, it's only 2 classes actually, but would that even work? 现在,我可以显式检查我在项目中使用的所有枚举了,实际上实际上只有2个类,但这还行得通吗?

if(args[i].GetType() == typeof(Priority)) { ... }

I mean, if type of args[i] is Priority.Normal, this would too evaluate as false. 我的意思是,如果args [i]的类型为Priority.Normal,则该结果也将为false。

How do I check an unknown object o has the type of a enumeration class? 如何检查未知object o具有枚举类的类型?

You can check IsEnum property. 您可以检查IsEnum属性。

args[i].GetType().IsEnum

Or 要么

if(args[i] is Enum)
{
}

Or 要么

bool isEnum = typeof(Enum).IsAssignableFrom(args[i].GetType());

Or 要么

bool isEnum = typeof(Enum).IsInstanceOfType(o);

尝试这个

 bool isEnum = o is Enum;

您可以利用System.TypeIsEnum属性

bool isEnum = typeof(YourType).IsEnum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM