简体   繁体   English

C#.net 4.5:泛型类从具有where约束的List继承

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

Working on a big project, I realized the following snippet : 在进行一个大型项目时,我意识到以下代码片段:

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(); 
    }
}

fails to compile the Crowd(Mother) function with the message "Unable to convert 'Test.Mother' to 'T'". 未能通过消息“无法将'Test.Mother'转换为'T'”来编译Crowd(Mother)函数。 Of course this seems deeply wrong to me, and the useFeature() is perfectly fine. 当然,这对我来说似乎是错误的,并且useFeature()非常好。 So what am I missing ? 那我想念什么呢?

NB: VS2012, win7 x64, .NET 4.5 注意:VS2012,win7 x64,.NET 4.5

The reason it doesn't compile is because it cannot work. 它不编译的原因是因为它无法工作。 Consider 考虑

public class MotherClass : Mother
{
    // ...
}

public class DaughterClass : Daughter
{
    // ...
}

void breakThings()
{
    new YouJustLostTheGame<Daughter>().Crowd(new MotherClass());
}

YouJustLostTheGame<Daughter> derives from List<Daughter> . YouJustLostTheGame<Daughter>List<Daughter>派生。 List<Daughter> can only store Daughter s. List<Daughter>只能存储Daughter Your Crowd takes a Mother as its parameter, so new MotherClass() is a valid argument. 您的Crowd将“ Mother作为其参数,因此new MotherClass()是有效的参数。 It then attempts to store an item in the list that the list isn't capable of holding. 然后,它将尝试将列表无法存储的项目存储在列表中。

You need to change the method signature to accept T instead of mother. 您需要更改方法签名以接受T而不是母亲。 crowd(T item).... 人群(T物品)....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM