开发者

Find Enum Value by Passed Parameter

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜