Foreach on enum类型在模板中

时间:2012-07-06 11:49:38

标签: c# templates .net-4.0 enums

enum MyEnum
{
type1,
type2,
type3
}

public void MyMethod<T>()
{
...
}

如何在枚举上使用MyMethod<T>来点击每个枚举?

我尝试了

foreach (MyEnum type in Enum.GetValues(typeof(MyEnum)))
{...}

但是仍然不知道如何在foreach中使用这个type MyMethod<T>为T

3 个答案:

答案 0 :(得分:4)

这是你想要做的吗?

class Program
{
    static void Main(string[] args)
    {
        EnumForEach<MyEnum>(MyMethod);
    }

    public static void EnumForEach<T>(Action<T> action)
    {
        if(!typeof(T).IsEnum)
            throw new ArgumentException("Generic argument type must be an Enum.");

        foreach (T value in Enum.GetValues(typeof(T)))
            action(value);
    }

    public static void MyMethod<T>(T enumValue)
    {
        Console.WriteLine(enumValue);
    }
}

写入控制台:

type1
type2
type3

答案 1 :(得分:0)

你可以做到

private List<T> MyMethod<T>()
{
    List<T> lst = new List<T>;

    foreach (T type in Enum.GetValues(source.GetType()))
    {
        lst.Add(type); 
    }

   return lst;
}

并将其命名为

List<MyEnum> lst = MyMethod<ResearchEnum>();

答案 2 :(得分:0)

此代码段演示了如何在消息框中将所有枚举值显示为链式字符串。以同样的方式,您可以使方法在枚举上执行所需的操作。

namespace Whatever
{
    enum myEnum
    {
        type1,type2,type3
    }

    public class myClass<T>
    {
        public void MyMethod<T>()
        {
            string s = string.Empty;
            foreach (myEnum t in Enum.GetValues(typeof(T)))
            {
                s += t.ToString();
            }
            MessageBox.Show(s);
        }
    }

    public void SomeMethod()
    {
        Test<myEnum> instance = new Test<myEnum>();
        instance.MyMethod<myEnum>(); //wil spam the messagebox with all enums inside
    }
}