Enum with methods for functionality (Combine Class / Enum)

后端 未结 2 1746

I may miss some sort of point here, if that\'s the case - please include that discussion as a part of my question :).

This is a shortened down and renamed sample of a wo

2条回答
  •  不要未来只要你来
    2021-02-03 19:47

    C# enums don't work well like this. However, you can implement your own "fixed set of values" fairly easily:

    public sealed class Foo
    {
        public static readonly Foo FirstValue = new Foo(...);
        public static readonly Foo SecondValue = new Foo(...);
    
        private Foo(...)
        {
        }
    
        // Add methods here
    }
    

    As it happens, one example I've got of this is remarkably similar to yours - DateTimeFieldType in Noda Time. Sometimes you might even want to make the class unsealed, but keep the private constructor - which allows you to create subclasses only as nested classes. Very handy for restricting inheritance.

    The downside is that you can't use switch :(

提交回复
热议问题