Foreach on enum types in template

和自甴很熟 提交于 2021-02-11 13:03:53

问题


enum MyEnum
{
type1,
type2,
type3
}

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

How to make forach on enum to fire MyMethod<T> on every enum?

I try something with

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

But still don't know how to use this type inside foreach with MyMethod<T> as T


回答1:


Is this what you are trying to do?

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);
    }
}

Writes to the console:

type1
type2
type3



回答2:


this code snippet demonstrates how to show all enum values as a chained string in a message box. In the same way you can make the method perform what you want on the enums.

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
    }
}



回答3:


You can do

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

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

   return lst;
}

and call it as

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


来源:https://stackoverflow.com/questions/11361635/foreach-on-enum-types-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!