假設我有以下代碼:似乎無法獲得通用協方差/逆變工作
public interface IBaseMessage { }
public interface IMessageProcessor<in T> where T : IBaseMessage {
void Process(T msg);
}
public class RRMessage : IBaseMessage {
//something here
}
public class BaseMessageProcessor {
//something here
}
public class RRMessageProcessor : BaseMessageProcessor, IMessageProcessor<RRMessage> {
public void Process(RRMessage msg) {
Console.WriteLine("Processed RRMessage");
}
}
public Dictionary<Type, IMessageProcessor<IBaseMessage>> MessageProcessors = new Dictionary<Type, IMessageProcessor<IBaseMessage>>();
[Test]
public void Test1() {
var msgProcessor = new RRMessageProcessor();
MessageProcessors.Add(typeof(RRMessage), msgProcessor);
}
我啓用逆變爲接口IMessageProcessor。爲什麼MessageProcessors.Add(typeof(RRMessage), msgProcessor);
原因編譯時錯誤:
Argument 2: cannot convert from 'RRMessageProcessor' to 'IMessageProcessor<IBaseMessage>'
現在看來似乎應該是能夠轉換,因爲RRMessageProcessor:IMessageProcessor<RRMessage:IBaseMessage>>
我怎樣才能得到這個工作?
'IMessageProcessor'是在'T'逆變所以你只能分配'IMessageProcessor '到'IMessageProcessor '對於某些亞型'RRMessage'的'TSub'。你想要的轉換將是不安全的,因爲它可以讓你在需要RRMessage參數時調用RRMessageProcessor.Process(new BaseMessage())。 –
Lee
你會如何改寫? – Denis
@Denis最好你可以在這裏做的是讓你的詞典'Dictionary'。 –
juharr