I have a SQL query builder method:
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.
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. 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. 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
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?
if(args[i].GetType() == typeof(Priority)) { ... }
I mean, if type of args[i] is Priority.Normal, this would too evaluate as false.
How do I check an unknown object o
has the type of a enumeration class?
You can check IsEnum property.
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.Type
的IsEnum
属性
bool isEnum = typeof(YourType).IsEnum
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.