Unable to convert List> to return type IList>

前端 未结 3 1287
名媛妹妹
名媛妹妹 2021-01-18 01:31

For level order traversal why does this exception occur? Following exception occurs:

Cannot implicitly convert type \'System.Collections.Generic

3条回答
  •  一生所求
    2021-01-18 02:15

    Pretty sure that if it compiles, doing a cast is a real bad idea. Here's why:

    public class myStupidList : IList
    {
    //implementation unimportant
    }
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
      var result = new List>();
      IList> imNotAListofLists = (IList>)result;
      imNotAListofLists.Add(new myStupidList());
      //result is not a very valid variable right now, is it?
    }
    

    As mentioned in my comment, these types of collection issues boil down to covariance and contravariance, and .NET does provide a lot of tools for dealing with them. (Such as various read-only collections and interfaces)

    ..Which, explains why you get your error as well. There is no implicit cast from List to List because that cast cannot succeed without breaking type-safety. (and as @Grax mentioned, neither derives from the other)

提交回复
热议问题