在一个大项目上工作时,我实现了以下代码片段:
public interface Mother
{
void CoolFeature();
}
public interface Daughter : Mother
{
}
public class YouJustLostTheGame<T> : List<T> where T : Mother
{
public void Crowd(Mother item)
{
this.Add(item);
}
public void useFeature()
{
this.Find(a => { return true; }).CoolFeature();
}
}
无法编译 Crowd(Mother)
函数,并显示消息“无法将 'Test.Mother' 转换为 'T'”。
当然,这对我来说似乎是非常错误的,而 useFeature()
完全没问题。
那么我错过了什么?
注意:VS2012、win7 x64、.NET 4.5
最佳答案
它无法编译的原因是它无法工作。考虑一下
public class MotherClass : Mother
{
// ...
}
public class DaughterClass : Daughter
{
// ...
}
void breakThings()
{
new YouJustLostTheGame<Daughter>().Crowd(new MotherClass());
}
YouJustLostTheGame<Daughter>
源自List<Daughter>
。 List<Daughter>
只能存储Daughter
s。您的Crowd
需要 Mother
作为其参数,所以 new MotherClass()
是一个有效的论点。然后,它尝试将列表无法容纳的项目存储在列表中。
关于C#.net 4.5 : Generic class inheriting from List with a where constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19312569/