我正在尝试将对象保存在通用的EventArgs类中,但由于EventHandler有一个接口,我很难完成此操作。有什么方法可以让这样的工作吗?
我的EventArgs类:
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; }
}
正在使用的界面:
public interface IMoveable
{
event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}
示例类用法:
public class SomeDevice : IMoveable
{
public event EventHandler<PositionChangedEventArgs<DeviceSpecificEventMessageArgs>> PositionChanged; //Compiler doesn't like this
}
答案 0 :(得分:9)
您需要将界面定义更改为以下内容:
public interface IMoveable<T>
{
event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}
您可以通过将类型传递给界面来消费它,如下所示:
public class SomeDevice : IMoveable<DeviceSpecificEventMessageArgs>
{
public event EventHandler<PositionChangedEventArgs<DeviceSpecificEventMessageArgs>> PositionChanged;
}
答案 1 :(得分:0)
这是因为您必须将接口声明为通用:
public interface IMoveable<T>
{
event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}