无法将派生类型隐式转换为其基类generics类型

我有以下类和接口:

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

现在,我有一个工厂将返回从ThingConsumer派生的对象,如:

 public class MyThingConsumer : ThingConsumer { } 

我的工厂目前看起来像这样:

 public static class ThingConsumerFactory where T : IThing { public static ThingConsumer GetThingConsumer(){ if (typeof(T) == typeof(Thing)) { return new MyThingConsumer(); } else { return null; } } } 

我遇到了这个错误: Error 1 Cannot implicitly convert type 'ConsoleApplication1.MyThingConsumer' to 'ConsoleApplication1.ThingConsumer'

有谁知道如何完成我在这里尝试的东西?

谢谢!

克里斯

如果你使ThingConsumer成为一个接口而不是一个抽象类,那么你的代码将按原样运行。

 public interface IThingConsumer where T : IThing { string Name { get; set; } } 

编辑

还需要一个改变。 在ThingConsumerFactoryThingConsumerFactory转换为返回类型IThingConsumer

 return (IThingConsumer)new MyThingConsumer(); 

编译器绊倒了从MyThingConsumerThingConsumer的转换,即使T:IThingMyThingConsumer:ThingconsumerThing:IThing 。 它有很多可以跳过的箍!

如果您使用return new MyThingConsumer() as ThingConsumer;则代码有效return new MyThingConsumer() as ThingConsumer; 而不是直接演员。 您知道结果永远不会为null ,并且编译器很高兴,因为它保证在运行时返回正确类型的值。

编辑:这是我用于测试的完整代码(在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); 

你需要像这样定义你的类我相信:

 public class MyThingConsumer : ThingConsumer 

原因是ThingConsumer已经在其定义中输入了: where T : IThing

现在,您可以使调用return new MyThingConsumer();

这应该与ThingConsumer的预期返回类型相匹配

编辑

抱歉混淆,这是应该工作的:

 public class MyThingConsumer : ThingConsumer where T : IThing 

 return new MyThingConsumer();