首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法将派生类型隐式转换为其基泛型类型

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

Stack Overflow用户
提问于 2012-09-08 03:09:28
回答 3查看 19.7K关注 0票数 28

我有以下类和接口:

代码语言:javascript
复制
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派生的对象,如下所示:

代码语言:javascript
复制
public class MyThingConsumer : ThingConsumer<Thing>
{
}

我的工厂现在看起来像这样:

代码语言:javascript
复制
public static class ThingConsumerFactory<T> where T : IThing
{
    public static ThingConsumer<T> GetThingConsumer(){
        if (typeof(T) == typeof(Thing))
        {
            return new MyThingConsumer();
        }
        else
        {
            return null;
        }
    }
}

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

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

谢谢!

克里斯

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-09-08 03:29:54

如果您将ThingConsumer<T>作为接口而不是抽象类,那么您的代码将按原样工作。

代码语言:javascript
复制
public interface IThingConsumer<T> where T : IThing
{
    string Name { get; set; }
}

编辑

还需要再做一次改变。在ThingConsumerFactory中,强制转换回返回类型IThingConsumer<T>

代码语言:javascript
复制
return (IThingConsumer<T>)new MyThingConsumer();
票数 11
EN

Stack Overflow用户

发布于 2012-09-08 04:06:18

编译器在从MyThingConsumerThingConsumer<T>的转换中遇到了困难,即使是T:IThingMyThingConsumer:Thingconsumer<Thing>Thing:IThing也是如此。对于它来说,这是一个相当多的障碍!

如果您使用return new MyThingConsumer() as ThingConsumer<T>;而不是直接转换,则代码可以正常工作。您知道结果永远不会是null,编译器很高兴,因为它在运行时得到了正确类型的返回值。

编辑:这里是我用来测试的完整代码(用Snippy编写):

代码语言:javascript
复制
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; }
}

public class MyThingConsumer : ThingConsumer<Thing>
{
}

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

...

var thing = ThingConsumerFactory<Thing>.GetThingConsumer();
Console.WriteLine(thing);
票数 4
EN

Stack Overflow用户

发布于 2012-09-08 03:12:42

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

代码语言:javascript
复制
public class MyThingConsumer<Thing> : ThingConsumer

原因是ThingConsumer在其定义中已经键入了以下内容:where T : IThing

现在,您可以调用return new MyThingConsumer<T>();

这又应该与ThingConsumer<T>的预期返回类型相匹配

编辑

很抱歉造成混乱,以下是应该起作用的方法:

代码语言:javascript
复制
public class MyThingConsumer<T> : ThingConsumer<T> where T : IThing

代码语言:javascript
复制
return new MyThingConsumer<T>();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12324020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档