2011-09-12 145 views
0

當我谷歌這麼多,我仍然不能理解代表和事件如何工作。代理和事件處理的問題

我想達到的目標是: 1級將被打動畫,當動畫結束時,它將委託/事件傳遞到2級,使2級會做動畫END東西。

我不知道如何編碼上述行爲?

回答

1

非常基本的事件實現...

public delegate void Class1AnimationCompletedHandler(object sender, EventArgs e); 

public class Class1 
{ 
    public event Class1AnimationCompletedHandler AnimationCompleted; 

    private void OnAnimationCompleted(EventArgs e) 
    { 
     if (this.AnimationCompleted != null) 
     { 
      // raises the AnimationCompleted event 
      this.AnimationCompleted(this, e); 
     } 
    } 

    public void Animate() 
    { 
     // do your animation steps here 

     this.OnAnimationCompleted(new EventArgs()); 
    } 
} 

public class Class2 
{ 
    private Class1 c1; 

    public Class2() 
    { 
     // initialize the class 
     c1 = new Class1(); 

     // attach this.Class1_AnimationCompleted to the AnimationCompleted event; 
     c1.AnimationCompleted += new Class1AnimationCompletedHandler(this.Class1_AnimationCompleted); 
    } 

    private void Class1_AnimationCompleted(object sender, EventArgs e) 
    { 
     // do your post-animation stuff here 
    } 

} 

link提供了關於如何創建活動作爲一個快速的例子。它針對VS 2003,但仍然適用。

+0

謝謝!最後我得到它的工作! –

0

把它看作是一個發佈者(暴露事件的類)和Subscriber(註冊處理器到事件的類)。

雖然在你提到的場景中,你能不能直接從Class1中調用Class2的DoSomething?

0

這裏有兩個類。我假設你在談論上面的例子。

public class ClassA 
{ 
    public event EventHandler Finished; 

    public ClassA() {} 

    public void Animate() 
    { 
     Console.WriteLine("ClassA instance animating."); 
     if (Finished != null) 
      Finished(this, null); 
    } 
} 

public class ClassB 
{ 
    public ClassB() {} 

    public void DoWork() 
    { 
     Console.WriteLine("ClassB instance doing work."); 
    } 
} 

然後,如果你有一個雙贏的形式你必須:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 

     ClassA a = new ClassA(); 
     a.Finished += delegate(object sender, EventArgs e) 
     { 
      ClassB b = new ClassB(); 
      b.DoWork(); 
     }; 
     a.Animate(); 
    } 
} 

和輸出是:

ClassA instance animating. 
ClassB instance doing work. 
0

所以Class1會暴露一個事件,到Class2將附上一個代表。當動畫結束時Class1會引發事件。那是你需要的嗎?

class Class1 
    { 
     public delegate void AnimationEndHandler(); 
     public event AnimationEndHandler AnimationEnded; 

     public void Animation() 
     { 
      //do the animation 
      Console.WriteLine("Animation ended. This is class 1"); 
      AnimationEnded(); 
     } 
    } 

    class Class2 
    { 
     public Class2(Class1 c1) 
     { 
      c1.AnimationEnded += new Class1.AnimationEndHandler(DoSomethingOnAnimationEnd); 
     } 

     public void DoSomethingOnAnimationEnd() 
     { 
      Console.WriteLine("Animation ended. This is class 2"); 
     } 
    } 

    static void Main(string[] args) 
    { 
     Class1 c1 = new Class1(); 
     Class2 c2 = new Class2(c1); 

     c1.Animation(); 
    }