我正在尝试在通过接口进行通信的几个类之间传递消息。但是,由于我喜欢尽可能通用,我遇到了问题,因为传入消息的消息类型可能与传出类型不同。我粘贴了一些代码以使其更清晰。
下面的代码无法编译,因为接口实现传递的类型与它应该添加传入消息的阻塞集合的类型不同。我希望能够发送可能与传入类型不同的类型(传入类型显然总是与阻塞集合中元素的类型匹配)。我能以某种方式绕过任何类型的转换或解析,即使这意味着我需要重新设计我的接口或类?
当涉及到使用接口并在递归、堆栈溢出错误等方面苦苦挣扎时,我仍然很新鲜。所以,如果你有什么建议我可以改进设计,或者只是一个快速修复,那么请帮助我学习。我非常渴望了解如何实现更好的模式。
谢谢
public interface IClientMessaging
{
void MessagePassing<U>(U message);
}
public class InProcessMessaging<T> : IClientMessaging
{
private Dictionary<Type, List<IClientMessaging>> Subscriptions;
public BlockingCollection<T> MessageBuffer;
public InProcessMessaging(Dictionary<Type, List<IClientMessaging>> subscriptions)
{
//Setup Message Buffer
MessageBuffer = new BlockingCollection<T>();
//Subscribe
Type type = typeof(T);
if (subscriptions.Keys.Contains(type))
{
subscriptions[type].Add(this);
}
else
{
subscriptions.Add(type, new List<IClientMessaging>());
subscriptions[type].Add(this);
}
Subscriptions = subscriptions;
}
public void SendMessage<U>(U message)
{
//Send message to each subscribed Client
List<IClientMessaging> typeSubscriptions = Subscriptions[typeof(U)];
foreach (IClientMessaging subscriber in typeSubscriptions)
{
subscriber.MessagePassing<U>(message);
}
}
public T ReceiveMessage()
{
return MessageBuffer.Take();
}
public bool ReceiveMessage(out T item)
{
return MessageBuffer.TryTake(out item);
}
//Interface Implementation
public void MessagePassing<U>(U message)
{
MessageBuffer.Add(message); //<-"Cannot convert from U to T" [this is because I want
//to send messages of a different type than the receiving type]
}
}