将通用T转换为System.Enum [英] Convert generic T into System.Enum

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

问题描述

我有一个 Enum s列表作为 IEnumerable< T> ,我需要在每个项目上循环并得到如下描述:

I have a list of Enums as an IEnumerable<T> and I need to loop on each item and get its description like this:

IEnumerable<T> values = (T[])Enum.GetValues(typeof(T));
foreach (Enum value in values)
{
    String mylist = Common.MyExtensions.getEnumDescription(value);
}

...

public static string getEnumDescription(Enum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes =    (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0)
    {
        return attributes[0].Description;
    }
    else
        return value.ToString();
}

这会在foreach部分产生错误

This produces an error at the foreach section


无法将 T转换为System.Enum。

cannot convert "T" to System.Enum.

不是 IEnumerable 首先是 System.Enum 的列表吗?
哪种类型的强制转换可以解决问题?

Isn't IEnumerable a list of System.Enum in the first place? What sort of cast can do the trick?

推荐答案

一种强制转换的方法是:

One way to do the cast is:

Enum enumValueError = (Enum)value;
//compiler error: Cannot convert type 'xxx' to 'System.Enum'
Enum enumValueNoError = value as Enum; 
//no error, but enumValueNoError will be null if value is not an Enum

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

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