【发布时间】:2014-05-21 22:09:12
【问题描述】:
我一直在尝试创建一个扩展方法,它适用于任何枚举,以返回其值。
不要这样做:
Enum.GetValues(typeof(BiasCode)).Cast<BiasCode>()
这样做会很好:
new BiasCode().Values()
如果没有 new 会更好,但这是另一个问题。
我有一个.NET fiddle,它的解决方案很接近(代码如下所示)。这段代码的问题是扩展方法返回List<int>。我想让它返回枚举值本身的列表。返回List<int> 并不可怕;这只是意味着我必须转换结果。
甚至有可能做到这一点吗?我尝试使扩展方法通用,但遇到了问题。这是我所能得到的最接近的:
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;
}
}
【问题讨论】:
-
在与 Jon Skeet 就这个问题进行了单独讨论后,我接受了甚至不是扩展方法的答案。似乎是正确的做法。与乔恩讨论:stackoverflow.com/a/23808495/279516
标签: c# enums extension-methods