不能隐式转换派生类型到它的基泛型类型类型、它的、隐式、基泛型

2023-09-03 04:47:05 作者:泪灼

我有以下的类和接口:

public interface IThing
{
    string Name { get; }
}

public class Thing : IThing
{
    public string Name { get; set; }
}

public abstract class ThingConsumer<T> where T : IThing
{
    public string Name { get; set; }
}

现在,我有一个工厂,将返回来自ThingConsumer等衍生的对象:

Now, I have a factory that will return objects derived from ThingConsumer like:

public class MyThingConsumer : ThingConsumer<Thing>
{
}

我厂目前看起来是这样的:

My factory currently looks like this:

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

我越来越绊倒了这个错误:错误1无法隐式转换类型'ConsoleApplication1.MyThingConsumer'到'ConsoleApplication1.ThingConsumer&LT; T&GT;

任何人都知道如何完成我试图在这里?

Anyone know how to accomplish what I'm attempting here?

谢谢!

克里斯

推荐答案

如果你让 ThingConsumer&LT; T&GT; 的接口,而不是一个抽象类,那么你的$ C $按c工作作为为。

If you make ThingConsumer<T> an interface rather than an abstract class, then your code will work as is.

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

修改

需要一个更多的变化。在 ThingConsumerFactory ,强制转换回返回类型 IThingConsumer&LT; T&GT;

One more change needed. In ThingConsumerFactory, cast back to the return type IThingConsumer<T>:

return (IThingConsumer<T>)new MyThingConsumer();