Casting string to type-safe-enum using user-defined conversion

后端 未结 2 1778
再見小時候
再見小時候 2021-01-19 02:03

In order to use Enum\'s in combination with strings, I implemented a StringEnum class based on https://stackoverflow.com/a/424414/1293385.

However I run into problem

2条回答
  •  没有蜡笔的小新
    2021-01-19 02:22

    You have to define an explicit cast operator on the derived class as well. The base class is not expected to know how to cast to a derived class.

    Since operators are static they are not inherited - the explicit cast operator is only defined between string and StringEnum. You can do this rather ugly double-cast yourself:

    DerivedStringEnum e = (DerivedStringEnum)(StringEnum)s
    

    Or in your derived class you can put: (edited after @ili pointed out my own oversight)

    public static explicit operator DerivedStringEnum(string name) 
    { 
      return (DerivedStringEnum)(StringEnum)name; 
    } 
    

提交回复
热议问题