不能隐式转换派生类型到它的基泛型类型 [英] Cannot implicitly convert derived type to its base generic type

查看:138
本文介绍了不能隐式转换派生类型到它的基泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的类和接口:

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

这篇关于不能隐式转换派生类型到它的基泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆