C#Events - 在一个解决方案中提升,订阅两个不同的项目

时间:2016-03-16 18:43:01

标签: c# events

我的目标是创建一个事件,在Project#1中引发事件,让Project#2订阅该事件,以便我可以在Project#2中找到一些代码。我被建议这样做,因为我无法引用Project#2中的代码。

我对事件并不熟悉,并且一直在研究最后一小时。是否有人可以提供有关如何执行此操作的示例代码?我现在所做的不起作用。

// Creating the event

public event EventHandler UpdateUIEvent;

// Raising the event in Project #1

protected override void ResetProperties() 
{
    this.filePath = string.Empty;
    EventArgs e = new EventArgs();
    UpdateUIEvent(this, e);  // this kills my program
}

// Subscribing to the event in Project #2

protected override void ClearAll()
{
    boEncrypt.UpdateUIEvent += new EventHandler ?? // Not sure how to subscribe here
    tbFile.text = string.Empty;
}

2 个答案:

答案 0 :(得分:1)

您已关闭...请照常阅读the docs,以便更好地了解需要采取的措施。

对于您的代码,这是我们要做的事情:

在项目1中,结合Michael HB的好建议,始终检查是否有任何订阅者。

public class ProjectOneClass
{
    public event EventHandler UpdateUIEvent;

    // other stuff     

    protected override void ResetProperties()
    {
        this.filePath = string.Empty;
        EventArgs e = new EventArgs();
        var handler = UpdateUIEvent;
        if (handler != null)
            UpdateUIEvent(this, e);
    }
}

然后在项目2中,您必须引用该事件,这意味着您还需要对包含它的类的引用。您可以在项目2中的类中定义一个方法,该方法与项目1中的事件具有相同的签名。在您的情况下(在许多情况下),此签名为void (object sender, EventArgs e)EventHandler是带有此签名的预定义delegate

"订阅"事件是将新方法添加到处理程序,例如pOne.UpdateUIEvent += SomeMethodWithTheSameSignature;您基本上说"每当调用UpdateUIEvent时,也要调用其他方法"。

现在我们知道我们可以在事件触发时调用一个方法,我们需要定义该事件。如果您想在事件触发时调用ClearAll(),那么方法正文中会发生什么。

public class ProjectTwoClass
{
    public ProjectOneClass pOne;

    // other stuff

    public ProjectTwoClass()
    {
        pOne = new ProjectOneClass();
        pOne.UpdateUIEvent += POneOnUpdateUIEvent;
    }

    public void POneOnUpdateUIEvent(object sender, EventArgs eventArgs)
    {
        ClearAll();
    }

    private void ClearAll()
    {
        tbFile.Text = string.Empty; // could probably just call tbFile.Clear();
    }
}

答案 1 :(得分:0)

在举起活动之前,您应该始终检查它是否为空。

protected override void ResetProperties()  
{
    this.filePath = string.Empty;
    EventArgs e = new EventArgs();
    var handler = UpdateUIEvent;
    if(handler != null)
       UpdateUIEvent(this, e);
}

即使你在不同的项目中,你也应该只关注“公共”关键字(内部或私人不起作用)。

在项目#2中,你将拥有

protected overeride void ClearAll() 
{
    boEncrypt.UpdateUIEvent += yourFunctionToTriggerWhenTheEventIsRaised;
    tbFile.text = string.Empty;
}
相关问题