Cannot implicitly convert derived type to its base generic type

后端 未结 3 1805
北海茫月
北海茫月 2020-12-20 10:56

I have the following classes and interfaces:

public interface IThing
{
    string Name { get; }
}

public class Thing : IThing
{
    public string Name { get         


        
3条回答
  •  醉梦人生
    2020-12-20 11:28

    The compiler is stumbling over the conversion from MyThingConsumer to ThingConsumer even though T:IThing and MyThingConsumer:Thingconsumer and Thing:IThing. Which is quite a few hoops for it to jump through!

    The code works if you use return new MyThingConsumer() as ThingConsumer; instead of a direct cast. You know the result will never be null, and the compiler is happy because it is guaranteed a return value of the right type at runtime.

    Edit: Here is the full code I used for testing (in Snippy):

    public interface IThing
    {
        string Name { get; }
    }
    
    public class Thing : IThing
    {
        public string Name { get; set; }
    }
    
    public abstract class ThingConsumer where T : IThing
    {
        public string Name { get; set; }
    }
    
    public class MyThingConsumer : ThingConsumer
    {
    }
    
    public static class ThingConsumerFactory where T : IThing
    {
        public static ThingConsumer GetThingConsumer()
        {
            if (typeof(T) == typeof(Thing))
            {
                return new MyThingConsumer() as ThingConsumer;
            }
            else
            {
                return null;
            }
        }
    }
    
    ...
    
    var thing = ThingConsumerFactory.GetThingConsumer();
    Console.WriteLine(thing);
    

提交回复
热议问题