Is it possible to cast integer to enum?
Possible Duplicate:
Cast int to Enum in C#
I got the following enum:
public enum detallistaDocumentStatus {
/// <remarks/>
ORIGINAL,
/// <remarks/>
COPY,
/// <remarks/>
REEMPLAZA,
/// <remarks/>
DELETE,
}
then I got a class property of type detallistaDocumentStatus:
public detallistaDocumentStatus documentStatus {
get {
return this.documentStatusField;
}
set {
this.documentStatusField = value;
}
}
In the real life the user will send us a number (1, 2, 3 or 4) representing each enum value in the order they are declared.
so, is it possible to cast like this?
det.documentStatus = (detallistaDocumentStatus)3;
if not, how could I get the enum value using an integer as an index, we are using a lot of enums, so we want to do something generic and reusable
Yes, 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.
It's also possible to cast Enum
to string
and vice versa.
public enum MyEnum
{
Value1 = 1,
Value2 = 2,
Value3 = 3
}
private static void Main(string[] args)
{
int enumAsInt = (int)MyEnum.Value2; //enumAsInt == 2
int myValueToCast = 3;
string myValueAsString = "Value1";
MyEnum myValueAsEnum = (MyEnum)myValueToCast; // Will be Value3
MyEnum myValueAsEnumFromString;
if (Enum.TryParse<MyEnum>(myValueAsString, out myValueAsEnumFromString))
{
// Put logic here
// myValueAsEnumFromString will be Value1
}
Console.ReadLine();
}
Yes it is possible. I use the following ENUM
public enum AccountTypes
{
Proposed = 1,
Open = 2
}
then when I call it I use this to get the value:
(int)AccountTypes.Open
And it will return the int value that I need which for the above will be 2.
From the C# 4.0 Specification:
1.10 Enums
Enum values can be converted to integral values and vice versa using type casts. For example
int i = (int)Color.Blue; // int i = 2;
Color c = (Color)2; // Color c = Color.Blue;
One additional thing to be aware of is that you are permitted to cast any integral value in the range of the enum's underlying type (by default that's int), even if that value doesn't map to one of the names in the enum declaration. From 1.10 Enums:
The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type.
So, the following is also permitted with the enum in your example:
det.documentStatus = (detallistaDocumentStatus) 42;
even though there's no enum name that has the value 42
.
上一篇: 你可以通过数字值来调用Enum吗?
下一篇: 是否有可能投出整数枚举?