【问题标题】:How do I associate an Event with a method Load?如何将事件与方法 Load 关联?
【发布时间】:2018-11-19 15:15:06
【问题描述】:

我想在每次使用 Load 方法时注册。为此,我想使用一个事件,就像它被调用时我想增加一个变量一样。

这个Load是一种从数据库中获取数据的方法,关键是要知道访问的次数。

谁能帮我理解如何创建这样一个事件。

方法定义:

protected override V Load(DbDataReader dr)

【问题讨论】:

标签: c# events delegates event-listener observers


【解决方案1】:

您似乎想为一个您已经知道的单一目的创建一个事件 - 计算访问数据库的次数。您可以以这种方式实现它:

public class Foo : TheClassThatDefinesLoad
{
    public event EventHandler Loaded;

    protected override V Load(DbDataReader dr)
    {
        var result = base.Load(dr);

        // An event handler with no listeners is null by default
        if (Loaded != null)
            Loaded.Invoke(this, new EventArgs());

        return result;
    }
}

// Somewhere in the calling code:
int loads = 0;
var foo = new Foo();
foo.Loaded += (sender, args) => loads += 1;

这不是线程安全的,但它是如何实现您想要的基本示例。但是,如果您使用的库已经提供了可以覆盖的虚拟方法,您是否还需要创建一个事件?您可以在没有事件的情况下轻松实现相同的目标:

public class Foo : TheClassThatDefinesLoad
{
    public int TotalLoads { get; private set; }

    protected override V Load(DbDataReader dr)
    {
        var result = base.Load(dr);
        TotalLoads += 1;
        return result;
    }
}

在这种情况下,我确实认为这里适合使用事件(我也认为 TheClassThatDefinesLoad 应该是定义事件的那个),但请记住,您并不总是需要使用事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多