这种结构可能会给你更多的灵活性,同时让你的IMsg
合同对消费者来说是一致的。
// the following three MsgId contracts don't have to be contracts at all (the actual types can be specified in generic IMsg directly), but if one ID type is wildly different in nature than the other, an interface such as this might make sense.
public interface IMsgId
{
// ?
}
public interface INewMsgId : IMsgId
{
}
public interface ILegacyMsgId : IMsgId
{
}
public interface IMsg<out TId>
where TId : IMsgId
{
TId MessageId { get; }
byte[] MsgBytes { get; }
}
// if it is sensible, you can use the following interfaces to create definitive new and legacy message contracts
public interface INewMsg : IMsg<INewMsgId>
{
}
public interface ILegacyMsg : IMsg<ILegacyMsgId>
{
}
这是一个实现示例:
public class LegacyMsgId : ILegacyMsgId
{
public LegacyMsgId(int id)
{
Id = id;
}
public int Id { get; private set; }
public override string ToString()
{
return "Legacy Message #" + Id;
}
}
public class NewMsgId : INewMsgId
{
public NewMsgId(int id)
{
Id = id;
}
public int Id { get; private set; }
public override string ToString()
{
return "New Message #" + Id;
}
}
public class NewMsg : INewMsg
{
public NewMsg(int id)
{
MessageId = new NewMsgId(id);
}
public NewMsgId MessageId { get; private set; }
INewMsgId IMsg<INewMsgId>.MessageId { get { return MessageId; } }
public byte[] MsgBytes { get; private set; }
}
public class LegacyMsg : ILegacyMsg
{
public LegacyMsg(int id)
{
MessageId = new LegacyMsgId(id);
}
public LegacyMsgId MessageId { get; private set; }
ILegacyMsgId IMsg<ILegacyMsgId>.MessageId { get { return MessageId; } }
public byte[] MsgBytes { get; private set; }
}
和用法:
var messages = new List<IMsg<IMsgId>>();
messages.Add(new NewMsg(20));
messages.Add(new LegacyMsg(11));
foreach(var message in messages)
{
Console.WriteLine(message.MessageId);
}