Can we define implicit conversions of enums in c#?

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

    You can't do implict conversions (except for zero), and you can't write your own instance methods - however, you can probably write your own extension methods:

    public enum MyEnum { A, B, C }
    public static class MyEnumExt
    {
        public static int Value(this MyEnum foo) { return (int)foo; }
        static void Main()
        {
            MyEnum val = MyEnum.A;
            int i = val.Value();
        }
    }
    

    This doesn't give you a lot, though (compared to just doing an explicit cast).

    One of the main times I've seen people want this is for doing [Flags] manipulation via generics - i.e. a bool IsFlagSet(T value, T flag); method. Unfortunately, C# 3.0 doesn't support operators on generics, but you can get around this using things like this, which make operators fully available with generics.

提交回复
热议问题