扩展方法来获取任何枚举的值 [英] Extension Method to Get the Values of Any Enum

查看:96
本文介绍了扩展方法来获取任何枚举的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建一个扩展方法,该方法适用于任何枚举,以返回其值。



而不是这样做:

  Enum.GetValues(typeof(BiasCode))。Cast< BiasCode>()

这样做很好:

  new BiasCode ).Values()

如果没有新的,甚至会更好,但是这是另一个问题。



我有一个 .NET小提琴有一个很近的解决方案(代码如下所示)。此代码的问题是扩展方法正在返回 List< int> 。我想让它返回枚举值本身的列表。返回列表< int> 并不可怕;这只是意味着我必须投出结果。



甚至可以这样做吗?我尝试使扩展方法泛型,但遇到问题。这是我能够得到的:

  using System; 
使用System.Linq;
使用System.Collections.Generic;

public class Program
{
public static void Main()
{
foreach(int biasCode in new BiasCode()。Values())
{
DisplayEnum((BiasCode)biasCode);
}
}

public static void DisplayEnum(BiasCode biasCode)
{
Console.WriteLine(biasCode);
}
}

public enum BiasCode
{
未知,
OC,
MPP
}

public static class EnumExtensions
{
public static List< int>值(this Enum theEnum)
{
var enumValues = new List< int>();
foreach(int enumValue in Enum.GetValues(theEnum.GetType()))
{
enumValues.Add(enumValue);
}

返回枚举值;
}
}


解决方案

你可以返回适当枚举类型的实例(使用反射创建),但其静态类型不能为列表< EnumType> 。这将需要 EnumType 作为该方法的通用类型参数,但是该类型必须被限制为仅枚举类型和在C#中是不可能的。



但是,您可以在实践中获得足够的接近(并添加运行时检查以将其打开),以便您可以编写一个如下所示的方法:

  public static IEnumerable< TEnum>值< TEnum>()
其中TEnum:struct,IComparable,IFormattable,IConvertible
{
var enumType = typeof(TEnum);

//可选运行时检查完整性
if(!enumType.IsEnum)
{
throw new ArgumentException();
}

返回Enum.GetValues(enumType).Cast< TEnum>();
}

您可以使用

  var values = Values< BiasCode>();我已经使方法返回 IEnumerable< TEnum> 而不是额外的LINQ-y风格的列表,但是您可以平均返回一个真正的列表,其中包含 .ToList()。返回值


I've been trying to create an extension method, that would work on any enum, to return its values.

Instead of doing this:

Enum.GetValues(typeof(BiasCode)).Cast<BiasCode>()

It would be nice to do this:

new BiasCode().Values()

It would even be better without new, but that's another issue.

I have a .NET fiddle that has a solution that's close (code shown below). The problem with this code is that the extension method is returning List<int>. I would like to have it return a list of the enum values itself. Returning List<int> isn't terrible; it just means I have to cast the result.

Is it even possible to do this? I tried making the extension method generic, but ran into problems. This is as close as I was able to get:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        foreach (int biasCode in new BiasCode().Values())
        {
            DisplayEnum((BiasCode)biasCode);
        }
    }

    public static void DisplayEnum(BiasCode biasCode)
    {
        Console.WriteLine(biasCode);    
    }
}

public enum BiasCode
{
    Unknown,
    OC,
    MPP
}

public static class EnumExtensions
{
    public static List<int> Values(this Enum theEnum)
    {
        var enumValues = new List<int>();
        foreach (int enumValue in Enum.GetValues(theEnum.GetType()))
        {
            enumValues.Add(enumValue);
        }

        return enumValues;
    }
}

解决方案

You can return an instance of the appropriate enum type (created using reflection), but its static type cannot be List<EnumType>. That would require EnumType to be a generic type parameter of the method, but then the type would have to be constrained to only enum types and that is not possible in C#.

However, you can get close enough in practice (and add runtime checks to top it off) so you can write a method that works like this:

public static IEnumerable<TEnum> Values<TEnum>()
where TEnum : struct,  IComparable, IFormattable, IConvertible
{
    var enumType = typeof(TEnum);

    // Optional runtime check for completeness    
    if(!enumType.IsEnum)
    {
        throw new ArgumentException();
    }

    return Enum.GetValues(enumType).Cast<TEnum>();
}

which you can invoke with

var values = Values<BiasCode>();

I have made the method return IEnumerable<TEnum> instead of a list for the extra LINQ-y flavor, but you can trivially return a real list with .ToList() on the return value.

这篇关于扩展方法来获取任何枚举的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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