gpt4 book ai didi

c# - 如何使用继承抽象类?

转载 作者:行者123 更新时间:2023-12-04 02:26:18 24 4
gpt4 key购买 nike

我需要一些有关继承类(抽象)示例的帮助。我无法使用我的函数 ToCSV(),因为我返回 BananaPart 列表,而 C# 需要 FruitPart 列表。怎么可能解决这个问题?

using System;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
FruitFactory fruitFactory = new FruitFactory();
Fruit myFruit = fruitFactory.Create("banana");

myFruit.FruitPart.ForEach(f => Console.WriteLine(f.ToString()));
}
}

public class FruitFactory {
public Fruit Create(string fruitType) {
switch(fruitType) {
case "banana":
return new Banana();
break;
default:
throw new Exception("undefined fruitType");
}
}
}

public abstract class Fruit {
protected string _name;
protected List<FruitPart> _fruitPart;

public Fruit() {
this._name = "A fruit";
}

public string Name { get { return this._name; } }
public List<FruitPart> FruitPart { get { return this._fruitPart; } }
}

public abstract class FruitPart { }

public class Banana : Fruit {
public Banana() : base() {
this._name = "banana";
this._fruitPart = ToCSV();
}

public List<BananaPart> ToCSV(){
return new List<BananaPart> { new BananaPart(5, "10"), new BananaPart(10, "20"), new BananaPart(20, "40") };
}
}

public class BananaPart : FruitPart {
private int _seed;
private string _dimensionPart;

public BananaPart (
int seed,
string dimensionPart
) {
this._seed = seed;
this._dimensionPart = dimensionPart;
}
}

我很高兴能进一步了解它!提前谢谢你!

最佳答案

你的代码没有编译的原因是因为 List<T>不是协变的。为了编译您的代码,您需要更改 List<T>IEnumerable<T>它有一个协变类型参数。所以变化是:

public abstract class Fruit {
protected string _name;
protected IEnumerable<FruitPart> _fruitPart;

public Fruit() {
this._name = "A fruit";
}

public string Name { get { return this._name; } }
public IEnumerable<FruitPart> FruitPart { get { return this._fruitPart; } }
}

您可以在此处了解有关协方差的更多信息:https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/

简而言之,协变让您可以根据其他两种类型的赋值兼容性推断出两种类型的赋值兼容性。因为,我们可以分配一个 BananaPartFruitPart ,我们可以推断出一个 IEnumerable<BananaPart>可以分配给IEnumerable<FruitPart> .

关于c# - 如何使用继承抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67370411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com