如何将通用枚举转换为 int? [英] How do I cast a generic enum to int?

查看:23
本文介绍了如何将通用枚举转换为 int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的小方法:

I have a small method that looks like this:

public void SetOptions<T>() where T : Enum
{
    int i = 0;
    foreach (T obj in Enum.GetValues(typeof(T)))
    {
        if (i == 0)
            DefaultOption = new ListItem(obj.Description(), obj.ToString());
        i++;
        DropDownList.Items.Add(new ListItem(obj.Description(), obj.ToString()));
    }
}

基本上,我从枚举填充下拉列表.Description()其实就是enum的扩展方法,所以T肯定是一个enum.

Basically, I populate a dropdown list from an enum. Description() is actually an extension method for enums, so T is definitely an enum.

但是,我想将 obj 就像您将任何枚举一样转换为它的索引,例如 (int)obj,但是我收到一个错误,说我不能将 T 转换为 int.有没有办法做到这一点?

However, I want to cast obj just as you would any enum to its index like this (int)obj, but I get an error saying I can't convert T to int. Is there a way to do this?

推荐答案

试试这个,

public void SetOptions<T>()
{
    Type genericType = typeof(T);
    if (genericType.IsEnum)
    {
        foreach (T obj in Enum.GetValues(genericType))
        {
            Enum test = Enum.Parse(typeof(T), obj.ToString()) as Enum;
            int x = Convert.ToInt32(test); // x is the integer value of enum
                        ..........
                        ..........
        }
    }
}

这篇关于如何将通用枚举转换为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆