在 C# 中将 List<Type> 设置为 List<IType>,其中 Type 实现 IType

问题描述 投票:0回答:1

为什么这条线

List<IFruit> l = apples;
不起作用?我该如何让它发挥作用?

    public interface IFruit {
        void Blend();
    }


    public class Apple : Fruit
    {
        public void Blend()
        {
            Console.WriteLine("Apple blending");
        }
    }

    public class Fruit : IFruit
    {
        public void Blend()
        {
            Console.WriteLine("Fruit blending");
        }
    }
    class Program 
    {
      static void Main(string[] args) 
      {
            Apple apple = new Apple();
            apple.Blend();
            Fruit fruit = new Fruit();
            fruit.Blend();
            List<Apple> apples = new();
            List<IFruit> l = apples;
      }
    }
c#
1个回答
0
投票

你缺少一个我!

    public class Apple : IFruit
    {
        public void Blend()
        {
            Console.WriteLine("Apple blending");
        }
    }

    public class Fruit : IFruit
    {
        public void Blend()
        {
            Console.WriteLine("Fruit blending");
        }
    }
    class Program 
    {
      static void Main(string[] args) 
      {
            Apple apple = new Apple();
            apple.Blend();
            Fruit fruit = new Fruit();
            fruit.Blend();
            List<Apple> apples = new();
            List<IFruit> l = apples;
      }
    }
© www.soinside.com 2019 - 2024. All rights reserved.