【问题标题】:Foreach on enum types in templateForeach 模板中的枚举类型
【发布时间】:2012-07-06 20:30:58
【问题描述】:
enum MyEnum
{
type1,
type2,
type3
}

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

如何在枚举上进行 forach 以在每个枚举上触发 MyMethod&lt;T&gt;

我尝试一下

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

但仍然不知道如何在 foreach 中使用这个type MyMethod&lt;T&gt; 为 T

【问题讨论】:

  • 你想做什么?

标签: c# templates .net-4.0 enums


【解决方案1】:

这是你想要做的吗?

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

【讨论】:

    【解决方案2】:

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

    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】:

      你可以的

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

      【讨论】:

      • 我认为你不会在枚举 MyEnum 上得到 GetType()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多