Parse string to enum type

后端 未结 8 1198
灰色年华
灰色年华 2020-11-29 09:04

I have an enum type like this as an example:

public Enum MyEnum {
    enum1, enum2, enum3 };

I\'ll read a string from config file. What I n

8条回答
  •  北海茫月
    2020-11-29 09:57

    I have a TryParseName method in UnconstrainedMelody, a library for delegate and enum utility methods which uses "inexpressible" constraints via some postbuild trickery. (Code using the library doesn't need a postbuild, just to be clear.)

    You would use it like this:

    Foo foo;
    bool parsed = Enums.TryParseName(name, out foo);
    

    I don't currently have a case-insensitive version, but I could easily introduce one if you wanted. Note that this doesn't try to parse numbers e.g. "12" like the built-in version does, nor does it try to parse comma-separated lists of flags. I may add the flags version later on, but I can't see much point in the numeric version.

    This is done without boxing and without execution time type checking. Having the constraint is really handy :)

    Please let me know if you'd find a case-insensitive parse useful...

提交回复
热议问题