0
点赞
收藏
分享

微信扫一扫

Note(15):C#使用Action泛型委托

女侠展昭 2022-03-30 阅读 35
c#

想一个例子,既要涉及到string类型,有要涉及到float类型的泛型,那就成绩管理吧。

1.声明委托。

public Action<string, float> UserEvent;

2.创建一个需要委托的方法,传的参数应该跟泛型参数保持一致。

   private void GetScore(string subject, double score)
        {

            MessageBox.Show(subject+":"+score);
        }

3.将该方法委托给UserEvent对象。

4.抛出一个委托对象,来触发事件。

             UserEvent += GetScore;
            UserEvent.Invoke("数学", 99.99);
            UserEvent.Invoke("英语", 99.98); 

 


全局代码:

  public Form2()
        {
            InitializeComponent();
        }

        public Action<string, double> UserEvent;


        private void Form2_Load(object sender, EventArgs e)
        {
            Form1 form1 = new Form1();
            form1.Show();
            GetMessageArgs.New_Text.Add("12");
            GetMessageArgs.New_Text.Add("34");
            GetMessageArgs.New_Text.Add("56");
            UserEvent += GetScore;
            UserEvent.Invoke("数学", 99.99);
            UserEvent.Invoke("英语", 99.98);

        }


        private void GetScore(string subject, double score)
        {

            MessageBox.Show(subject+":"+score);
        }


效果演示:

 

举报

相关推荐

0 条评论