简体   繁体   中英

How to cast my own enum type to generic enum type?

How can I cast my own enum type to generic enum type?

public enum MyEnum
    {
        First,
        Second
    }

    public class MyEnumParser<TEnum>
        where TEnum : struct, Enum
    {
        public static TEnum Parse(string value)
        {
            switch (default(TEnum))
            {
                case MyEnum _: return MyEnum.First;  // Error in this line of code
                default: throw new ArgumentOutOfRangeException($"Type {nameof(TEnum)} not supported.");
            }
        }
    }

The compiler won't let me convert the type, even though I'm explicitly checking the type in the switch:

Cannot implicitly convert type 'ConsoleApp1.MyEnum' to 'TEnum'

If I try to explicitly cast the type, I get another error:

case MyEnum _: return (TEnum)MyEnum.First;

Cannot convert type 'ConsoleApp1.MyEnum' to 'TEnum'

Upd. I am currently working on System.Text.JSON serializer. This is simplified example.The method must be generic. Gradually, I will add all my other enumerations to the serializer. I started with one.

The simplest way to cast your custom enum type MyEnum to generic enum type TEnum is to use the next approach:

case MyEnum _: return (TEnum) (object) MyEnum.First;

Here are links to similar problems:

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