简体   繁体   中英

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'". Of course this seems deeply wrong to me, and the useFeature() is perfectly fine. So what am I missing ?

NB: 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> . List<Daughter> can only store Daughter s. Your Crowd takes a Mother as its parameter, so new MotherClass() is a valid argument. 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. crowd(T item)....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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