下面是一段愚蠢的代码片段,我想保留一份请求列表,以便将它们与响应相匹配。我从中删除了很多代码以简化它,它可能没有多大意义。
以下代码中的注释表示错误。模板类型我做错了什么?
static void Main(string[] args)
{
Request request = new Request();
Response response = SendReceive<Response>(request);
Console.ReadLine();
}
static T SendReceive<T>(IMessage request) where T: IMessage
{
T results = default(T);
OutstandingRequest<T> outstandingRequest = new OutstandingRequest<T>();
_waitingForResponses.Add(outstandingRequest as OutstandingRequest<IMessage>);
// Above line of code adds a null to the list because outstandingRequest (type OutstandingRequest<T>)
//is not of type OutstandingRequest(IMessage) even though T is restricted to be of type IMessage
// Do stuff like send, and wait for a response, return results.
return results;
}
static List<OutstandingRequest<IMessage>> _waitingForResponses = new List<OutstandingRequest<IMessage>>();
public interface IMessage
{
void Qaax();
}
public class Request : IMessage
{
public void Qaax() { }
}
public class Response : IMessage
{
public void Qaax() { }
}
public class OutstandingRequest<T> where T : IMessage
{
public T Response { get; set; }
}
}