2010-12-16 96 views
2

代码片段1)不编译,我需要如果我由于某种原因想要按照原样进行测试,请在剪辑2) 中进行演员制作。但为什么编译器不能进行这种转换,例如铸造用于剪断3)将IList投射到IEnumerable

1)

static IDictionary<int, IEnumerable<int>> DoStuff() 
{ 
    var test = new Dictionary<int, IList<int>>() { { 1, new List<int>() { 1, 2 } } }; 
    return test; 
} 

2)

static IDictionary<int, IEnumerable<int>> DoStuff() 
{ 
    var test = new Dictionary<int, IList<int>>() { { 1, new List<int>() { 1, 2 } } }; 
    return test.ToDictionary(item => item.Key, item => (IEnumerable<int>)item.Value); 
} 

3)

static IEnumerable<int> DoStuff() 
{ 
    var test = new List<int>() { 1, 2 }; 
    return test; 
} 

回答

3

Variance .NET 4的支持,但在你的情况下,netiher IDictionary的<>也不IList的<>是变异类型,因此不能自动转换为另一个IDictionary <>。

3

这是因为IDictionary<int, IList<int>>不继承/实现IDictionary<int, IEnumerable<int>>

您的第一个例子可以改变这一点,应该工作:

static IDictionary<int, IEnumerable<int>> DoStuff() 
{ 
    var test = new Dictionary<int, IEnumerable<int>>() { { 1, new List<int>() { 1, 2 } } }; 
    return test; 
}