simple custom event

后端 未结 4 1755

I\'m trying to learn custom events and I have tried to create one but seems like I have a problem

I have created a Form, static class and custom event. What I\'m tr

4条回答
  •  独厮守ぢ
    2020-11-27 12:15

    This is an easy way to create custom events and raise them. You create a delegate and an event in the class you are throwing from. Then subscribe to the event from another part of your code. You have already got a custom event argument class so you can build on that to make other event argument classes. N.B: I have not compiled this code.

    public partial class Form1 : Form
    {
        private TestClass _testClass;
        public Form1()
        {
            InitializeComponent();
            _testClass = new TestClass();
            _testClass.OnUpdateStatus += new TestClass.StatusUpdateHandler(UpdateStatus);
        }
    
        private void UpdateStatus(object sender, ProgressEventArgs e)
        {
            SetStatus(e.Status);
        }
    
        private void SetStatus(string status)
        {
            label1.Text = status;
        }
    
        private void button1_Click_1(object sender, EventArgs e)
        {
             TestClass.Func();
        }
    
    }
    
    public class TestClass
    {
        public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
        public event StatusUpdateHandler OnUpdateStatus;
    
        public static void Func()
        {
            //time consuming code
            UpdateStatus(status);
            // time consuming code
            UpdateStatus(status);
        }
    
        private void UpdateStatus(string status)
        {
            // Make sure someone is listening to event
            if (OnUpdateStatus == null) return;
    
            ProgressEventArgs args = new ProgressEventArgs(status);
            OnUpdateStatus(this, args);
        }
    }
    
    public class ProgressEventArgs : EventArgs
    {
        public string Status { get; private set; }
    
        public ProgressEventArgs(string status)
        {
            Status = status;
        }
    }
    

提交回复
热议问题