C#.net 4.5 : Generic class inheriting from List with a where constraint

标签 c# generics .net-4.5

在一个大项目上工作时,我实现了以下代码片段:

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/

相关文章:

c# - Razor:在 foreach 循环中获取上一个/下一个对象属性

c# - 如何获取通用列表中的最后一个对象?

c# - 如何在此上下文中调用接口(interface)方法?

c# - 从奇数格式解析日期时间

c# - IIS动态压缩 'ALREADY_CONTENT_ENCODING'

c# - 关闭我的应用程序会干扰我的 Form1_FormClosing 事件

泛型的 C# 类型检查

c# - 具有约束的泛型方法的重载解析问题

F# 脚本无法加载 .Net 4.5?

c# - 如何使用反射创建通用对象