Converting a method argument into an enum
This question already has an answer here:
Just check if the int is a valid value for Status and then do a conversion.
public string doSomething(string param1, int status)
{
if (IsValidEnum<Status>(status))
{
Account.Status = (Status)status;
}
...
}
private bool IsValidEnum<T>(int value)
{
var validValues = Enum.GetValues(typeof(T));
var validIntValues = validValues.Cast<int>();
return validIntValues.Any(v => v == value);
}
In de else of the if you can throw an exception if you wish.
well of course you can do that. just try and see.
you can also cast the other way
(int)Account.Status
it's possible to cast Enum to int and vice versa, because every Enum is actually represented by an int per default. You should manually specify member values. By default it starts from 0 to N.
if you try to convert an enum value that does not exist it'll work, but wont give you an enum value if you try to compare it the any value you have in the enum
Yes, you can do a straight cast from int
to enum
(given that an enum
representation of that integer exists).
If you need to check whether the enum
exists before parsing use Enum.IsDefined ie
if (Enum.IsDefined(typeof(Status), status))
{
Account.Status = (Status)status;
}
链接地址: http://www.djcxy.com/p/22526.html
上一篇: 在知道类型时将int转换为Enum
下一篇: 将方法参数转换为枚举