C#:将枚举类型作为参数传递

标签 c# enums c#-2.0

我尝试使用以下代码将枚举转换为通用列表

public static List<T> ToList<T>(Type t) where T : struct
{
    return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}

它成功地遵守了。

我试着用下面的代码调用上面提到的方法

 enum Fruit
    {
        apple = 1,
        orange = 2,
        banana = 3
    };

    private List<Fruit> GetFruitList()
    {
        List<Fruit> allFruits = EnumHelper.ToList(Fruit);
        return allFruits;
    }

导致如下错误

Compiler Error Message: CS0118: 'default.Fruit' is a 'type' but is used like a 'variable'

所以我确定如何将枚举类型作为参数传递。

最佳答案

public static List<T> ToList<T>() where T : struct
{
    return Enum.GetValues(typeof(T)).Cast<T>().ToList();
}

enum Fruit
{
    apple = 1,
    orange = 2,
    banana = 3
};

private List<Fruit> GetFruitList()
{
    List<Fruit> allFruits = EnumHelper.ToList<Fruit>();
    return allFruits;
}

关于C#:将枚举类型作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5168326/

相关文章:

c# - 使用 .resx 文件在 LocalHost 上工作但不在服务器 MVC 上工作的本地化

python - 将 C 枚举导入到 python 中而不包含完整的 header ?

c# - 将数组的一部分添加到列表的内存有效方法

c#-2.0 - 单击按钮时触发文本更改事件

c# - 文件夹选取器在移动设备上引发异常

c# - 从密码中导出加密 key

c# - 如何在 EF Core 中使用 LINQ 将原始数据类型列表与实体连接起来?

sql - 如何在 Redshift 中创建枚举?

java - 枚举上的基本方法调用

asp.net - 如何获取对象类型(不是字符串)中 DropDownList 中的选定值?