2016-02-28 76 views
2

我嘗試使用下面的代碼來實現泛型類:字典中的泛型類

interface IBasicInput<T> where T : InputOutputConfig 
{ 
    void Configure<T>(ConfigurationDictionary<T> conf) where T : InputOutputConfig; 
} 

public class ConfigurationDictionary<T> : Dictionary<string,T> where T : InputOutputConfig 
{  
} 

public abstract class InputOutputConfig 
{ 
} 

public class SpecificInputConfig : InputOutputConfig 
{ 
}  

public class GenericInput<T> : IBasicInput<T> where T : InputOutputConfig 
{ 
    ConfigurationDictionary<T> configuration; 

    public GenericInput() 
    { 
     configuration = null; 
    } 

    public void Configure<T>(ConfigurationDictionary<T> _conf) where T : InputOutputConfig 
    { 
     configuration = new ConfigurationDictionary<T>(); 
     foreach (KeyValuePair<string,T> kvp in _conf) 
     { 

     } 
    } 
} 

的isssue是configuration = new ConfigurationDictionary<T>();產生錯誤。

錯誤CS0029無法隱式轉換類型 'ConfigurationDictionary [GenericsTest,版本= 1.0.0.0,文化=中立,公鑰=空]' 到「ConfigurationDictionary [GenericsTest,版本= 1.0.0.0,文化=中立,公鑰= null]'

這條消息對我沒有意義,因爲它基本上說它不能將「typeA」轉換爲「typeA」。有人能解釋這段代碼有什麼問題嗎?

+0

你的問題,是因爲你有兩個通用的類型參數稱爲' T'在你的'Configure'方法的範圍內 – jamespconnor

回答

7

您已使用您的函數T模板參數將您的班級'T模板參數遮蔽起來。他們可能不一樣。

要麼給你的內心像TT2也許另一名產品總數下降,如果你想用你的類T反正:

public class GenericInput<T> : IBasicInput<T> where T : InputOutputConfig 
{ 
    ConfigurationDictionary<T> configuration; 

    public GenericInput() 
    { 
     configuration = null; 
    } 

    public void Configure<T2>(ConfigurationDictionary<T2> _conf) where T2 : InputOutputConfig 
    { 
     // in this line, you need the class template T, not the inner T2 
     configuration = new ConfigurationDictionary<T>(); 

     foreach (KeyValuePair<string,T2> kvp in _conf) 
     { 

     } 
    } 
}