jeudi 11 août 2016

How to define events and properties in a decorator .net

I defined an interface which has an event and a property defined as follows.

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

I then created a class and using it, every thing works fine.

Now I want to extend this class using a decorator. I am not sure how to handle the event. For the property I think I am clear, just want confirmation.

I defined the decorator class as follows.

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;

}

Aucun commentaire:

Enregistrer un commentaire