关于模板中的枚举类型的Foreach [英] Foreach on enum types in template

查看:58
本文介绍了关于模板中的枚举类型的Foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

enum MyEnum
{
type1,
type2,
type3
}

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

如何在枚举上进行分支以在每个枚举上触发 MyMethod< T> ?

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

我尝试与

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

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

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

推荐答案

您要这样做吗?

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

这篇关于关于模板中的枚举类型的Foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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