Can we define implicit conversions of enums in c#?

前端 未结 13 2356
孤街浪徒
孤街浪徒 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 19:05

    enums are largely useless for me because of this, OP.

    I end up doing pic-related all the time:

    the simple solution

    classic example problem is the VirtualKey set for detecting keypresses.

    enum VKeys : ushort
    {
    a = 1,
    b = 2,
    c = 3
    }
    // the goal is to index the array using predefined constants
    int[] array = new int[500];
    var x = array[VKeys.VK_LSHIFT]; 
    

    problem here is you can't index the array with the enum because it can't implicitly convert enum to ushort (even though we even based the enum on ushort)

    in this specific context, enums are obsoleted by the following datastructure . . . .

    public static class VKeys
    {
    public const ushort
    a = 1,
    b = 2, 
    c = 3;
    }
    
    0 讨论(0)
提交回复
热议问题