设计问题——多态事件处理
我目前正在尝试减少当前项目中事件句柄的数量。我们有多个通过 USB 发送数据的系统。我目前有一个例程来读取消息并解析初始标头详细信息以确定消息来自哪个系统。标头有点不同,所以我创建的 EventArgs 不一样。然后我通知所有“观察者”这一变化。所以我现在拥有的是以下内容:
public enum Sub1Enums : byte
{
ID1 = 0x01,
ID2 = 0x02
}
public enum Sub2Enums : ushort
{
ID1 = 0xFFFE,
ID2 = 0xFFFF
}
public class MyEvent1Args
{
public Sub1Enums MessageID;
public byte[] Data;
public MyEvent1Args(Sub1Enums sub1Enum, byte[] data)
{
MessageID = sub1Enum;
Data = data;
}
}
public class MyEvent2Args
{
public Sub2Enums MessageID;
public byte[] Data;
public MyEvent2Args(Sub2Enums sub2Enum, byte[] data)
{
MessageID = sub2Enum;
Data = data;
}
}
Form1 代码
public class Form1
{
public delegate void TestHandlerCurrentlyDoing(MyEvent1Args eventArgs1);
public delegate void TestHandlerCurrentlyDoingAlso(MyEvent2Args eventArgs2);
public event TestHandlerCurrentlyDoing mEventArgs1;
public event TestHandlerCurrentlyDoingAlso mEventArgs2;
public Form1()
{
mEventArgs1 += new TestHandlerCurrentlyDoing(Form1_mEventArgs1);
mEventArgs2 += new TestHandlerCurrentlyDoingAlso(Form1_mEventArgs2);
}
void Form1_mEventArgs2(MyEvent2Args eventArgs2)
{
// Do stuff here
Sub2Enums mid = my_event2_args.MessageID;
byte[] data = my_event2_args.Data;
}
void Form1_mEventArgs1(MyEvent1Args eventArgs1)
{
// Do stuff here
Sub1Enums mid = my_event1_args.MessageID;
byte[] data = my_event1_args.Data;
}
在解析算法中,我有这样的东西,基于它是哪条消息:
void ParseStuff()
{
if (mEventArgs1 != null)
{
mEventArgs1(new MyEvent1Args(Sub1Enums.ID1, new byte[] { 0x01 }));
}
if (mEventArgs2 != null)
{
mEventArgs2(new MyEvent2Args(Sub2Enums.ID2, new byte[] { 0x02 }));
}
}
我真正想做的是:
public class Form1
{
public delegate void TestHandlerDesired(MyEvent1Args eventArgs1);
public delegate void TestHandlerDesired(MyEvent2Args eventArgs2);
public event TestHandlerDesired mEventArgs;
public Form1()
{
mEventArgs += new TestHandlerDesired (Form1_mEventArgs1);
mEventArgs += new TestHandlerDesired (Form1_mEventArgs2);
}
}
由于模棱两可的原因,我们不能这样做。所以我的问题是什么是解决这个问题的更好方法?