Why can I not assign a List of concrete types to a List of that concrete's interface?

前端 未结 8 1463
悲哀的现实
悲哀的现实 2020-12-19 02:17

Why does this not compile?

public interface IConcrete { }

public class Concrete : IConcrete { }

public class Runner
{
    public static void Main()
    {
         


        
8条回答
  •  隐瞒了意图╮
    2020-12-19 03:21

    The accepted solution is quite inefficient for large lists, and completely unnecessary. You can change the signature of your method ever so slightly to make the code work without any conversions, either implicit or explicit:

    public class Runner
    {
        public static void Main()
        {
            var myList = new List();
            DoStuffWithInterfaceList(myList);  // compiler doesn't allow this
        }
    
        public static void DoStuffWithInterfaceList(List listOfInterfaces)
            where T: IConcrete
        { }
    }
    

    Notice that the method is now generic and uses a type constraint to ensure that it can only be called with lists of IConcrete subtypes.

提交回复
热议问题