日期:2014-05-18  浏览次数:21129 次

不同类 值传递与值接收
类y (比如说是Form 窗体),类x(某实现类)
类x 在某个逻辑需要传递消息给类y,但是类x没有声明 类y的引用.当x需要传递消息给y时 y要立刻做出反应.

y 里面不想有 Timer 类似的循环监听

能否给个良好的架构!!!!



------解决方案--------------------
C# code
delegate\event的方法:

类X:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;

namespace WindowsFormsApplication1
{
    public class ClassX
    {
        public delegate void MessageDelegate(string strMsg);
        public event MessageDelegate MessageEvent;

        public void Test()
        {
            if (MessageEvent != null)
            {
                MessageEvent("类X for循环开始.");
            }

            for (int i = 0; i < 100000;i++ )
            {
                Application.DoEvents();
            }

            if (MessageEvent != null)
            {
                MessageEvent("类X for循环结束.");
            }
        }
    }
}

Form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private ClassX cls = new ClassX();
        private void Form1_Load(object sender, EventArgs e)
        {
            cls.MessageEvent += MessageFunction;
        }

        private void MessageFunction(string strMsg)
        {
            MessageBox.Show(strMsg);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cls.Test();
        }
    }
}