简体   繁体   中英

How to get Type of Nullable<Enum>?

How can you do something like the following in C#?

Type _nullableEnumType = typeof(Enum?);

I guess a better question is why can't you do that when you can do this:

Type _nullableDecimalType = typeof(decimal?);

Enum is not an enum - it is the base-class for enums, and is a reference-type (ie a class ). This means that Enum? is illegal, as Nullable<T> has a restriction that T : struct , and Enum does not satisfy that.

So: either use typeof(Nullable<>).MakeGenericType(enumTypeKnownAtRuntime) , or more simply, typeof(EnumTypeKnownAtCompileTime?)

You might also want to note that:

Enum x = {some value};

is a boxing operation , so you should usually avoid using Enum as a parameter etc.

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.

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