How to TryParse for Enum value?

前端 未结 14 1010
终归单人心
终归单人心 2020-11-29 00:22

I want to write a function which can validate a given value (passed as a string) against possible values of an enum. In the case of a match, it should return th

14条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 00:49

    As others have said, you have to implement your own TryParse. Simon Mourier is providing a full implementation which takes care of everything.

    If you are using bitfield enums (i.e. flags), you also have to handle a string like "MyEnum.Val1|MyEnum.Val2" which is a combination of two enum values. If you just call Enum.IsDefined with this string, it will return false, even though Enum.Parse handles it correctly.

    Update

    As mentioned by Lisa and Christian in the comments, Enum.TryParse is now available for C# in .NET4 and up.

    MSDN Docs

提交回复
热议问题