【发布时间】:2011-08-20 00:49:34
【问题描述】:
我想将从一个具有泛型的类派生的不同类型的对象添加到基类型列表中。我得到这个编译错误
Error 2 Argument 1: cannot convert from 'ConsoleApplication1.Stable' to 'ConsoleApplication1.ShelterBase<ConsoleApplication1.AnimalBase>' C:\Users\ysn\Desktop\ConsoleApplication1\ConsoleApplication1\Program.cs 43 26 ConsoleApplication1
我看不出问题,您能否提供一种替代方法来做这种事情?
abstract class AnimalBase { public int SomeCommonProperty;}
abstract class ShelterBase<T> where T : AnimalBase
{
public abstract List<T> GetAnimals();
public abstract void FeedAnimals(List<T> animals);
}
class Horse : AnimalBase { }
class Stable : ShelterBase<Horse>
{
public override List<Horse> GetAnimals()
{
return new List<Horse>();
}
public override void FeedAnimals(List<Horse> animals)
{
// feed them
}
}
class Duck : AnimalBase { }
class HenHouse : ShelterBase<Duck>
{
public override List<Duck> GetAnimals()
{
return new List<Duck>();
}
public override void FeedAnimals(List<Duck> animals)
{
// feed them
}
}
class Program
{
static void Main(string[] args)
{
List<ShelterBase<AnimalBase>> shelters = new List<ShelterBase<AnimalBase>>();
///////////////////////////// following two lines do not compile
shelters.Add(new Stable());
shelters.Add(new HenHouse());
/////////////////////////////
foreach (var shelter in shelters)
{
var animals = shelter.GetAnimals();
// do sth with 'animals' collection
}
}
}
【问题讨论】:
-
您使用的是什么版本的 .Net?如果是 .Net 4,则需要查看 Covariance。
标签: c# generics inheritance compiler-errors