2014-07-20 3 views
0

지금까지 내가이벤트 사전을 만들려면 어떻게해야합니까?

private Dictionary<T, event Action> dictionaryOfEvents; 

가 이런 식으로 뭔가를 할 수 있고, 이벤트의 사전을 갖고 싶어?

+1

사전 및 이벤트는 무엇입니까? –

+0

저장하려는 메소드 나 호출이 있습니까? – TaW

+0

왜 이벤트 컬렉션이 필요하다고 생각하는지 설명하십시오. 그러면 기술 문제에 답하는 대신 문제를 해결하는 데 도움이됩니다. –

답변

6

이벤트 사전을 사용할 수는 없지만 대리인 사전을 가질 수는 있습니다.

private Dictionary<int, YourDelegate> delegates = new Dictionary<int, YourDelegate>(); 

여기에서 YourDelegate은 모든 대리인 유형이 될 수 있습니다.

+0

나는 그렇게 하겠지만, List 를 사전의 값 부분으로 사용하여 키당 여러 개의 YourDelegates를 가질 수 있습니다. –

+3

@IanHern'List 를 사용할 필요가 없습니다.'YourDelegate'만으로 충분합니다. (대리인을 결합 할 수 있습니다.) (http://msdn.microsoft.com/en-IN/library/ms173175.aspx) –

+0

사실 일단 델리게이트를 함께 호출하면 델리게이트를 결합/추가 할 수 있습니다. 이것은 단지 하나가 원하는 것일 수도 있지만 그렇지 않을 수도 있습니다. 그들을 자유롭게 액세스하는 것이 바람직하다면 어쩌면 List 또는 심지어 초, 내부 사전이 올바른 해결책이 될 수 있습니다. – TaW

2

이벤트 유형이 아니지만 작업입니다. 예를 들면 다음과 같이 쓸 수 있습니다 :

private void button1_Click(object sender, EventArgs e) 
{ 
    // declaration 
    Dictionary<string, Action> dictionaryOfEvents = new Dictionary<string, Action>(); 

    // test data 
    dictionaryOfEvents.Add("Test1", delegate() { testMe1(); }); 
    dictionaryOfEvents.Add("Test2", delegate() { testMe2(); }); 
    dictionaryOfEvents.Add("Test3", delegate() { button2_Click(button2, null); }); 

    // usage 1 
    foreach(string a in dictionaryOfEvents.Keys) 
    { Console.Write("Calling " + a + ":"); dictionaryOfEvents[a]();} 

    // usage 2 
    foreach(Action a in dictionaryOfEvents.Values) a(); 

    // usage 3 
    dictionaryOfEvents["test2"](); 

} 

void testMe1() { Console.WriteLine("One for the Money"); }   
void testMe2() { Console.WriteLine("One More for the Road"); } 
관련 문제