2011-05-17 36 views
5

請考慮下面的代碼:<往前往IDictionary <StudentType,IList <Student>>?>學生類型列表<Student>>?

class Student 
{ 
} 

enum StudentType 
{ 
} 

static void foo(IDictionary<StudentType, IList<Student>> students) 
{ 
} 

static void Main(string[] args) 
{ 
    Dictionary<StudentType, List<Student>> studentDict = 
        new Dictionary<StudentType, List<Student>>(); 

    foo(studentDict); 

    ... 
} 

有錯誤:

error CS1503: Argument '1': cannot convert from 'System.Collections.Generic.Dictionary>' to 'System.Collections.Generic.IDictionary>'

有什麼辦法來調用foo的功能?

+0

你實現自己的藏品?如果沒有,看不到有什麼理由避免使用'static void foo(Dictionary > students)'來解決這個問題。 – 2011-05-17 10:48:09

+0

'static void foo(IDictionary > students) '只是爲了簡單。代替'foo()'IDictionary <>傳遞給我的應用程序的另一部分,所以有必要使用'IDictionary <>'和'IList <>'來提供一個抽象。 – 2011-05-17 10:55:22

回答

6

你可以使用LINQ的ToDictionary方法來創建一個新的字典,其中值有正確的類型:

static void Main(string[] args) 
{ 
    Dictionary<StudentType, List<Student>> studentDict = new Dictionary<StudentType, List<Student>>(); 
    var dicTwo = studentDict.ToDictionary(item => item.Key, item => (IList<Student>)item.Value); 
    foo(dicTwo); 
} 
+0

謝謝!這正是我需要的。 – 2011-05-17 11:04:20

3

你將會建立一個正確類型的新字典,將數據從舊數據複製到新數據庫。

或者,您可以將原始字典更改爲正確的類型開始。

無論哪種方式,不,你不能施放字典。

其原因限制如下:

  1. 本詞典收錄類型學生的價值觀
  2. 你可以有實現IStudent
  3. 的方法,你給的cast'ed多種類型字典可能會嘗試將另一個IStudent填充到字典中,即使它不是學生
+0

我不明白這個答案。問題中沒有IStudent。 – richb 2015-07-08 23:25:23

0

將studentDict的創建更改爲:

Dictionary<StudentType, IList<Student>> studentDict = new Dictionary<StudentType, IList<Student>>(); 
+0

對不起,但它不是一個選項。我需要這個創作。 – 2011-05-17 10:52:59

+0

你能解釋一下你爲什麼需要這個創作嗎?您可以將該列表添加到該創建中。如果你已經在你的代碼的其他地方創建了對象,那麼你將需要通過創建一個新的字典並轉換值來轉換它。 – IndigoDelta 2011-05-17 11:00:14

+0

因爲我需要在字典中調用List特定的成員函數。 – 2011-05-17 11:02:15

相關問題