Can we define implicit conversions of enums in c#?

前端 未结 13 2377
孤街浪徒
孤街浪徒 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:49

    You probably could, but not for the enum (you can't add a method to it). You could add an implicit conversion to you own class to allow an enum to be converted to it,

    public class MyClass {
    
        public static implicit operator MyClass ( MyEnum input ) {
            //...
        }
    }
    
    MyClass m = MyEnum.One;
    

    The question would be why?

    In general .Net avoids (and you should too) any implicit conversion where data can be lost.

提交回复
热议问题