假設下面的代碼(請閱讀我的問題在最終的類代碼註釋):如何通過一個通用類作爲參數的非通用類的構造函數
//This is my Generic Class
public class ClientRequestInfo<K, V>
{
public string Id { get; set; }
private Dictionary<K, V> parameters;
public ClientRequestInfo()
{
parameters = new Dictionary<K, V>();
}
public void Add(K key, V value)
{
parameters.Add(key, value);
}
}
public class ProcessParameters()
{
private void CreateRequestAlpha()
{
ClientRequestInfo<int, string> info = new ClientRequestInfo<int, string>();
info.Add(1, "Hello");
SynchRequest s = new SynchRequest(info);
s.Execute();
}
private void CreateRequestBeta()
{
ClientRequestInfo<int, bool> info = new ClientRequestInfo<int, bool>();
info.Add(1, true);
SynchRequest s = new SynchRequest(info);
s.Execute();
}
}
public class SynchRequest
{
//What type should I put here?
//I could declare the class as SynchRequest<K, V> but I don't want
//To make this class generic.
private ClientRequestInfo<????,?????> info;
private SynchRequest(ClientRequestInfo<?????,?????> requestInfo)
{
//Is this possible?
this.info = requestInfo;
}
public void Execute()
{}
}
爲什麼你不希望使用一個通用的SynchRequest? – AnthonyWJones 2009-09-29 17:06:39
你可以談談你將在信息成員的Execute()中做什麼嗎?這可以爲功能相當的答案提供基礎。 – joshperry 2009-09-29 17:12:37
因爲類SynchRequest由其他類項目的打了個SynchRequest的目的是運行服務,不提供任何類型的有關客戶的信息。還有一些類使用SynchRequest,並且不指定或需要任何客戶端信息。所以不是使這個類變得通用的好方法。 (SynchRequest有另一個空的構造函數) – Ioannis 2009-09-29 17:16:15