Microsoft .NET Pertanyaan dan Jawaban Wawancara
Question: Can a subscriber subscribe to more than one publisher?Answer: Yes, also - here's some code for a publisher with multiple subscribers.using System; namespace Console1 { class Class1 { delegate void myDelegate(int parameter1); static event myDelegate myEvent; static void AStaticMethod(int param1) { Console.WriteLine(param1); } static void Main(string[] args) { MyClass myInstance = new MyClass(); myEvent += new myDelegate(myInstance.AMethod); myEvent += new myDelegate(AStaticMethod); myEvent(1); //both functions will be run. Console.ReadLine(); } } class MyClass { public void AMethod(int param1) { Console.WriteLine(param1); } } } Another example: using System; using System.Threading; namespace EventExample { public class Clock { public delegate void TwoSecondsPassedHandler(object clockInstance, TimeEventArgs time); //The clock publishes an event that others subscribe to public event TwoSecondsPassedHandler TwoSecondsPassed; public void Start() { while(true) { Thread.Sleep(2000); //Raise event TwoSecondsPassed(this, new TimeEventArgs(1)); } } } public class TimeEventArgs : EventArgs { public TimeEventArgs(int second) { seconds += second; instanceSeconds = seconds; } private static int seconds; public int instanceSeconds; } public class MainClass { static void Main(string[] args) { Clock cl = new Clock(); // add some subscribers cl.TwoSecondsPassed += new Clock.TwoSecondsPassedHandler(Subscriber1); cl.TwoSecondsPassed += new Clock.TwoSecondsPassedHandler(Subscriber2); cl.Start(); Console.ReadLine(); } public static void Subscriber1(object clockInstance, TimeEventArgs time) { Console.WriteLine("Subscriber1:" + time.instanceSeconds); } public static void Subscriber2(object clockInstance, TimeEventArgs time) { Console.WriteLine("Subscriber2:" + time.instanceSeconds); } } } |
Simpan untuk Revisi
Bookmark item ini, tandai sebagai sulit, atau masukkan ke dalam set revisi.
Masuk untuk menyimpan bookmark, pertanyaan sulit, dan set revisi.
Apakah ini membantu? Ya Tidak
Most helpful rated by users:
- Name 10 C# keywords.
- What is public accessibility?
- .NET Stands for?
- What is private accessibility?
- What is protected accessibility?