我定义了一个具有事件和属性定义如下的接口。
public interface IMyInterface
{
event EventHandler SomeEvent;
string GetName();
string IpAddress { get; set; }
}
然后我创建了一个类并使用它,每个东西都可以正常工作。
现在我想使用装饰器扩展这个类。 我不确定如何处理此事件。对于物业,我认为我很清楚,只是想要确认。
我将decorator类定义如下。
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;
}
答案 0 :(得分:1)
你不应该处理这个事件,你可以提出这个事件:
像:
if(SomeEvent != null)
SomeEvent(this, EventArgs.Empty);
C#6.0中的
SomeEvent?.Invoke(this, EventArgs.Empty);
答案 1 :(得分:1)
您可以使用add
和remove
将事件的订阅和取消订阅转发到要装饰的元素。这样,如果您订阅LoggerDecorator.SomeEvent
,则实际上是订阅了内部IMyInterface.SomeEvent
。
在您的情况下,应如下所示:
public class LoggerDecorator : IMyInterface
{
(...)
public event EventHandler SomeEvent
{
add => _MyInterface.SomeEvent += value;
remove => _MyInterface.SomeEvent -= value;
}
}
答案 2 :(得分:0)
好的,我想我得到了答案。
以下是ctor。
_MyInterface.SomeEvent += _MyInterface_SomeEvent;
,事件处理程序方法如下。
private void _MyInterface_SomeEvent(object sender, EventArgs e)
{
var someEvent = SomeEvent;
if (someEvent != null)
{
someEvent(this, e);
}
}
完整的实施如下。
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;
// This is change 1.
_MyInterface.SomeEvent += _MyInterface_SomeEvent;
}
// This is change 2
private void _MyInterface_SomeEvent(object sender, EventArgs e)
{
var someEvent = SomeEvent;
if (someEvent != null)
{
someEvent(this, e);
}
}
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;
}
}
public event EventHandler SomeEvent;
}