为什么与接口参数的构造函数用于代替最派生参数类型的构造函数?

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

我遇到了我们的代码中的问题,其中某些信息正在消失。我没有找到一个修复它,但我不太明白这种行为。我做了简单起见一个例子:

公共接口

public interface IFruit
{
    Color Color { get; set; }
}

2.派生类:

public class Apple : IFruit
{
    public int Radius { get; set; }
    public Color Color { get; set; }

    public Apple(IFruit fruit)
    {
        Color = fruit.Color;
    }

    public Apple(Apple apple)
    {
        Color = apple.Color;
        Radius = apple.Radius;
    }

    public Apple(Color color, int radius)
    {
        Color = color;
        Radius = radius;
    }

    public override string ToString()
    {
        return $"I'm a {Color.ToString()} apple with a radius of {Radius}cm";
    }
}

public class Banana : IFruit
{
    public int Length { get; set; }
    public Color Color { get; set; }

    public Banana(IFruit fruit)
    {
        Color = fruit.Color;

    }

    public Banana(Banana banana)
    {
        Color = banana.Color;
        Length = banana.Length;
    }

    public Banana(Color color, int lenght)
    {
        Color = color;
        Length = Length;
    }


    public override string ToString()
    {
        return $"I'm a {Color.ToString()} banana with a length of {Length}cm";
    }
}

测试代码:

[TestClass]
public class FruitTests
{
    [TestMethod]
    public void WhichConstructorIsUsed()
    {
        var fruits = new List<IFruit>();
        fruits.Add(new Apple(Colors.Red, 5));
        fruits.Add(new Banana(Colors.Yellow, 20));

        var clonedFruits = fruits.Select(f => new Apple(f));

        Console.WriteLine(string.Join("\n", clonedFruits));
    }
}

产量

我是一个红苹果与0厘米半径

我是黄苹果与0厘米半径

我不明白的是

请注意,红苹果失去了它的半径值。据我所知,香蕉失去它的信息,但我不明白为什么,对于苹果的实例,构造苹果(IFruit水果)正在使用,而不是苹果公司(Apple苹果)构造函数。这是一个苹果,它只是在碱基类型的类型化的列表。

我预计香蕉例如使用更普通的构造函数,而不是苹果的实例。

c# polymorphism
1个回答
0
投票

在点您检索从列表中它的类型是f为你申报你的列表,IFruit List<IFruit>。当你调用f => new Apple(f)你调用苹果构造与IFruit,而不是一个具体类型。

如果你是从列表中显式转换Apple你会得到完全访问所有的具体类型的属性。

© www.soinside.com 2019 - 2024. All rights reserved.