当我只有枚举的类型时,如何获取枚举的整数值

Mic*_*hel 4 c# enums

我认为这个问题需要一些代码:

private TypeValues GetEnumValues(Type enumType, string description)
        {
            TypeValues wtv = new TypeValues();
            wtv.TypeValueDescription = description;
            List<string> values = Enum.GetNames(enumType).ToList();
            foreach (string v in values)
            {
                //how to get the integer value of the enum value 'v' ?????
                wtv.TypeValues.Add(new TypeValue() { Code = v, Description = v });
            }
            return wtv;

        }
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

GetEnumValues(typeof(AanhefType), "some name");
Run Code Online (Sandbox Code Playgroud)

GetEnumValues函数中我有枚举的值.所以我迭代值,我想得到该枚举值的整数值.

所以我的值是'红色'和'绿色',我也希望得到0和1.

当我在我的函数中使用Enum时,我可以从字符串创建枚举值并将其转换为该枚举,然后将其转换为int,但在这种情况下,我没有枚举本身,但只有类型的枚举.

我尝试将实际枚举作为参数传递,但我不允许将枚举作为参数传递.

所以现在我被困了.....

Ste*_*eve 5

private TypeValues GetEnumValues(Type enumType, string description)
        {
            TypeValues wtv = new TypeValues();
            wtv.TypeValueDescription = description;
            List<string> values = Enum.GetNames(enumType).ToList();
            foreach (string v in values)
            {
                //how to get the integer value of the enum value 'v' ?????

               int value = (int)Enum.Parse(enumType, v);

                wtv.TypeValues.Add(new TypeValue() { Code = v, Description = v });
            }
            return wtv;

        }
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/essfb559.aspx

Enum.Parse将获取一个Type和一个String,并返回对其中一个枚举值的引用 - 然后可以简单地将其转换为int.


Ser*_*kiy 5

尝试

(int)Enum.Parse(enumType, v)
Run Code Online (Sandbox Code Playgroud)