Can we define implicit conversions of enums in c#?

前端 未结 13 2359
孤街浪徒
孤街浪徒 2020-11-30 18:37

Is it possible to define an implicit conversion of enums in c#?

something that could achieve this?

public enum MyEnum
{
    one = 1, two = 2
}

MyEnu         


        
13条回答
  •  离开以前
    2020-11-30 18:40

    If you define the base of the enum as a long then you can perform explicit conversion. I don't know if you can use implicit conversions as enums cannot have methods defined on them.

    public enum MyEnum : long
    {
        one = 1,
        two = 2,
    }
    
    MyEnum number = MyEnum.one;
    long i = (long)number;
    

    Also, be aware with this that an uninitalised enumeration will default to the 0 value, or the first item - so in the situation above it would probably be best to define zero = 0 as well.

提交回复
热议问题