C#事件不适用于不同的解决方案



我有一个包含3个项目的解决方案;1个类库项目,2个WinForms项目。

假设两个WinForms是(VendorUI(和(CustomerUI(,(DemoLibrary(是类库。

类库代码:

namespace DemoLibrary
{
public delegate void Notify();
public static class Catalogue
{
public static event Notify NewProduct;
public static void AddNewProduct()
{
if (NewProduct != null)
NewProduct.Invoke();
}
}
}

VendorUI代码:

using System;
using System.Windows.Forms;
using DemoLibrary;
namespace VendorUI
{
public partial class Vendor : Form
{
public Vendor()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Catalogue.AddNewProduct();
}
}
}

客户UI代码:

using System;
using System.Windows.Forms;
using DemoLibrary;
using OtherWinFormUI;
namespace CustomerUI
{
public partial class Customer : Form
{
public Customer()
{
InitializeComponent();
Catalogue.NewProduct += Catalogue_NewProduct;
}
void Catalogue_NewProduct()
{
label1.Text += string.Format("A new product is added to the catalogue ({0})n", DateTime.Now);
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[System.STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
(new OtherWinFormUI.Vendor()).Show();
Application.Run(new Customer());
}
}
}

一切都很顺利,直到我将每个项目分离到不同的解决方案,然后分别运行CustomerUI和VendorUI,事件不再工作,VendorUI添加新产品时也不会通知CustomerUI,我确保引用是正确的,但事件仍然没有启动。

当我把项目分开时,我做错了什么?

因为单独的项目在不同的进程中运行,所以通过引用其他库来订阅事件实际上不会产生任何结果,因为事件实际上并不是在寻找它们的进程中触发的。

您可以使用诸如ManagedSpy之类的变通方法来订阅来自其他进程的事件,或者使用一些Win32魔术来挂接到其他进程的消息传递循环中。

相关内容

最新更新