考慮下面的接口和類聲明。如何創建從實現接口的基類派生的實例列表?
public interface IMessage
{
string Body { get; set; }
}
public abstract class MessageBase : IMessage
{
public string Body { get; set; }
}
public class MessageA : MessageBase { }
public class MessageB : MessageBase { }
public class MessageC : MessageBase { }
public interface IMessageProcessor<T> where T : IMessage
{
Action<T> ProcessorAction { get; set; }
}
public abstract class MessageProcessorBase<T> : IMessageProcessor<T> where T : MessageBase
{
public Action<T> ProcessorAction { get; set; }
}
public class MessageAProcessor : MessageProcessorBase<MessageA> { }
public class MessageBProcessor : MessageProcessorBase<MessageB> { }
public class MessageCProcessor : MessageProcessorBase<MessageC> { }
現在我要聲明,像這樣的處理器實例列表,但無法弄清楚什麼泛型類型可以讓我的任何派生處理器類型添加到列表中。
var processors = new List<???>();
processors.Add(new MessageAProcessor());
processors.Add(new MessageBProcessor());
processors.Add(new MessageCProcessor());
我曾嘗試:
// compiles but throws InvalidCastException
var processors = new List<IMessageProcessor<IMessage>>();
processors.Add((IMessageProcessor<IMessage>)new MessageAProcessor());
和
// compiles but throws InvalidCastException
var processors = new List<IMessageProcessor<MessageBase>>();
processors.Add((IMessageProcessor<MessageBase>)new MessageAProcessor());
和
// won't compile
var processors = new List<MessageProcessorBase<MessageBase>>();
processors.Add((MessageProcessorBase<MessageBase>)new MessageAProcessor());
我應該這個列表的類型是什麼?我知道我必須在這裏錯過一些明顯的東西。任何幫助在這裏將不勝感激。謝謝!
您可以將'ProcessMessage'實現移至基址:'var msg = message as T' –
@AlekseyL。好點,修正了,謝謝 – 3615
@ 3615謝謝 - 現在我明白了。 –