Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Event Args In Interface

I'm trying to save an object in a generic EventArgs class but because the EventHandler has an interface, I'm having difficulty accomplishing this. Any way to get something like this working?

My EventArgs class:

public class PositionChangedEventArgs<T>
{
   public PositionChangedEventArgs(byte position, T deviceArgs)
   {
       Position = position;
       DeviceArgs = deviceArgs;
   }

   public byte Position { get; private set; }
   public T DeviceArgs { get; private set; }
}

Interface being used:

public interface IMoveable
{
    event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}

Example class usage:

public class SomeDevice : IMoveable
{
   public event EventHandler<PositionChangedEventArgs<DeviceSpecificEventMessageArgs>> PositionChanged; //Compiler doesn't like this
}
like image 397
Robert Avatar asked Jan 20 '23 10:01

Robert


1 Answers

You need to change your interface definition to the following:

public interface IMoveable<T>
{
    event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}

You can consume it by passing the type to the interface like so:

public class SomeDevice : IMoveable<DeviceSpecificEventMessageArgs>
{
   public event EventHandler<PositionChangedEventArgs<DeviceSpecificEventMessageArgs>> PositionChanged; 
}
like image 82
Doctor Jones Avatar answered Jan 23 '23 00:01

Doctor Jones