Rob*_*ert 4 c# generics c#-4.0
我试图在一个通用的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; }
}
Run Code Online (Sandbox Code Playgroud)
正在使用的接口:
public interface IMoveable
{
event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}
Run Code Online (Sandbox Code Playgroud)
示例类用法:
public class SomeDevice : IMoveable
{
public event EventHandler<PositionChangedEventArgs<DeviceSpecificEventMessageArgs>> PositionChanged; //Compiler doesn't like this
}
Run Code Online (Sandbox Code Playgroud)
您需要将接口定义更改为以下内容:
public interface IMoveable<T>
{
event EventHandler<PositionChangedEventArgs<T>> PositionChanged;
}
Run Code Online (Sandbox Code Playgroud)
您可以通过将类型传递给接口来使用它,如下所示:
public class SomeDevice : IMoveable<DeviceSpecificEventMessageArgs>
{
public event EventHandler<PositionChangedEventArgs<DeviceSpecificEventMessageArgs>> PositionChanged;
}
Run Code Online (Sandbox Code Playgroud)