65.9K
CodeProject 正在变化。 阅读更多。
Home

在 C# 中使用接口引用事件 - 一种简单的方法

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2012 年 9 月 6 日

CPOL

1分钟阅读

viewsIcon

21727

通过在“EventReference”实例中代理事件,以接口的形式传递事件引用。

引言

以下文章展示了一种使用接口和泛型“引用”事件的简单方法。为了简单起见,它使用了 Actions 和 Functions。

背景 

我能找到的唯一相关的文章是:

源代码概述

一个非泛型事件引用描述

public interface IEventReference { }

可用于约束更具体的,但仍然是泛型的事件描述接口。

public interface IActionEventReference<I> where I : IEventReference
{
    event Action Event;
}
public interface IActionEventReference<I, P1> where I : IEventReference
{
    event Action<P1> Event;
}

public interface IFuncEventReference<I, R> where I : IEventReference
{
    event Func<R> Event;
}
public interface IFuncEventReference<I, P1, R> where I : IEventReference
{
    event Func<P1, R> Event;
}

使用方法  

考虑一个暴露一些事件的类,例如

public class ClassExposingEvents
{
  public event Func<bool> BeforeCancel;
}

添加“引用”BeforeCancel事件的可能性可以分为三个步骤

首先,可以创建一个用于具体事件引用的接口:

public interface IBeforeCancelEventReference : IEventReference { event Func<bool> BeforeCancel; }

并将其添加到提供事件的类中

pulic class ClassExposingEvents : IBeforeCancelEventReference
{
  public event Func<bool> BeforeCancel;
}

其次,可以定义一个事件的代理类(我通常将其定义为事件容器的子类,但这并非必要)

public class BeforeCancelEventRef : 
         IFuncEventReference<IBeforeCancelEventReference, bool>
{
  IBeforeCancelEventReference e;
  public BeforeCancelEventRef(IBeforeCancelEventReference eventContainer) { e = eventContainer; }
  public event Func<bool> Event
  {
    add { e.BeforeCancel += value; }
    remove { e.BeforeCancel -= value; }
  }
}

最后,所有需要引用BeforeCancel事件的组件只需要一个BeforeCancelEventRef类的实例(通常作为接口返回,并由工厂或其他适当的方式创建)。

要使用引用,我们可以简单地从引用的Event属性中添加和删除目标

IFuncEventReference<IBeforeCancelEventReference, bool> bce = ...;
bce.Event += ...;

值得关注的点  

文章中没有涵盖异常和性能方面。

历史 

  • 2012/09/06:提交了第一个版本。
© . All rights reserved.