开发者

Find Enum Value by Passed Parameter

开发者 https://www.devze.com 2022-12-14 04:40 出处:网络
I have an enum like this : public enum Priority { Low = 0, Medium = 1, Urgent = 2 } And I want to get the for example Priority.Low by passing like Enum.GetEnumVar(Priority,0) which should return 开

I have an enum like this :

public enum Priority
{
   Low = 0,
   Medium = 1,
   Urgent = 2 
}

And I want to get the for example Priority.Low by passing like Enum.GetEnumVar(Priority,0) which should return 开发者_开发知识库Priority.Low

How can I accomplish that ?

Thank you in advance.


Simply cast it to the enum type:

int value = 0;
Priority priority = (Priority)value;
// priority == Priority.Low

Note that you can cast any int to Priority, not only those which have a name: (Priority)42 is valid.


Like this:

Priority fromInt = (Priority)0;
Assert.That(fromInt, Is.EqualTo(Priority.Low));

Also, this works:

Priority fromString = (Priority)Enum.Parse(typeof(Priority), "Low");
Assert.That(fromString, Is.EqualTo(Priority.Low));
0

精彩评论

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