2012-07-06 5 views

답변

3

어떻게 하시겠습니까?

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

을하고 호출 할 수 있습니다 T로 MyMethod<T>와 foreach는 내부에이 type를 사용하는 방법을 모르는 여전히

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

하지만 뭔가를 시도 예 :

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

열거 형 MyEnum에서 GetType()을 얻지 못할 것이라고 생각합니다. – V4Vendetta

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 
    } 
} 
관련 문제