开发者

Parsing user provided enumeration values in C#

开发者 https://www.devze.com 2023-02-03 22:01 出处:网络
I\'d like for the user to provide an e开发者_Go百科num name, say \"Color\", and a value, say \"red\", and tell them whether or not that is a member value of that enumeration, or if the enumeration eve

I'd like for the user to provide an e开发者_Go百科num name, say "Color", and a value, say "red", and tell them whether or not that is a member value of that enumeration, or if the enumeration even exists.

How can I do this?

In the past, I have used Type.GetType("UserProvidedType").Parse / Convert.ChangeType, but this doesn't appear to work when the user provided type is an enumeration. Please see: Parsing to primitive types, based on user input in c# for past solutions that don't appear to work in this context.

Thanks.


var type = Type.GetType("YourNameSpace.Color");
var belongs = Enum.GetNames(type).Any(o => o == "Red");
0

精彩评论

暂无评论...
验证码 换一张
取 消