开发者

Cast IList to IEnumerable

Code snip 1) does not compile, and I need e.g. to make the cast as in snip 2) if I for some reason want test declared as it is. But why can't the compiler make that cast, this is e.g. the cast for snip 3)

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 IEnum开发者_Python百科erable<int> DoStuff()
{
  var test = new List<int>() { 1, 2 };
  return test;
}


Variance is supported in .NET 4, but in your case, netiher IDictionary<> nor IList<> are variant types, hence can't be automatically converted to another IDictionary<>.


It is because IDictionary<int, IList<int>> does not inherit/implement IDictionary<int, IEnumerable<int>>

Your first example can be changed to this and should work:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜