我定义了一个接口(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;
}
最佳答案
您可以使用add
和remove
将事件的订阅和取消订阅转发到正在装饰的元素。这样,如果您订阅 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/