c# - 如何在装饰器中定义事件和属性

我定义了一个接口(interface),它有一个事件和一个定义如下的属性。

public interface IMyInterface
{
    event EventHandler SomeEvent;
    string GetName();
    string IpAddress { get; set; }
}

然后我创建了一个类并使用它,一切正常。

现在我想使用装饰器扩展这个类。 我不确定如何处理该事件。对于属性我想我很清楚,只是想确认一下

我定义的装饰器类如下。

public class LoggerDecorator : IMyInterface
{
    private readonly IMyInterface _MyInterface;
    private readonly ILog _MyLog;
    public LoggerDecorator(IMyInterface myInterface, ILog myLog)
    {
        if (myInterface == null)
            throw new ArgumentNullException("IMyInterface is null");
        _MyInterface = myInterface;

        if (myLog == null)
            throw new ArgumentNullException("ILog instance is null");
        _MyLog = myLog;

    }

    public string GetName()
    {
        // If needed I can use log here
        _MyLog.Info("GetName method is called.");
        return _MyInterface.GetName();
    }

    // Is this the way to set properties?
    public string IpAddress
    {
        get
        {
            return _MyInterface.IpAddress;
        }

        set
        {
            // If needed I can use log here
            _MyLog.Info("IpAddress is set.");
            _MyInterface.IpAddress = value;
        }
    }


    // But How to handle this evetn?? Please help. I am not clear about this.
    public event EventHandler SomeEvent;

}

最佳答案

您可以使用addremove 将事件的订阅和取消订阅转发到正在装饰的元素。这样,如果您订阅 LoggerDecorator.SomeEvent,您实际上订阅了内部 IMyInterface.SomeEvent

在您的情况下,它应该如下所示:

public class LoggerDecorator : IMyInterface
{
    (...)

    public event EventHandler SomeEvent
    {
        add => _MyInterface.SomeEvent += value;
        remove => _MyInterface.SomeEvent -= value;
    }
}

https://stackoverflow.com/questions/38889309/

相关文章:

laravel - 为什么在 Laravel 中注销路由不起作用?

oracle - 更新分区键,不允许行移动

angular - 在 Angular 2 模板中使用普通 POST 表单会导致 : "Templa

java - 将 List> 转换为 int[][]

php - 上传文件在php中不起作用

php - 如何过滤此 PHP 数组对象中的唯一对象

django - 不可散列类型 : 'list' error when trying to add

string - 如何在 go 模板中连接两个字符串?

python - 如何通过 Django 查看上传的文本文件?

php - 使用 cronjob 运行 php 文件中的函数