无法返回约束泛型的具体实现

3

我有一些关于泛型的问题,但我找不出我的错误。

给定以下代码:

public interface IMyInterface { }

public class MyImplementation : IMyInterface { }

public interface IMyFactory<T> where T : class, IMyInterface
{
    T Create();
}

public class MyFactory<T> : IMyFactory<T> where T : class, IMyInterface
{
    public T Create()
    {
        // Complex logic here to determine what i would like to give back
        return new MyImplementation(); // <--- red squigglies - Cannot implicitly convert type 'ConsoleApp18.MyImplementation' to 'T'
    }
}

如果我像这样使用 return new MyImplementation() as T;,它就能正常工作了,不再出现错误。
如果我像这样使用 return (T)new MyImplementation();,我会得到一个代码建议,提示我删除不必要的转换。(是的,我也认为为什么不能返回具体实现,因为它与 T 兼容?)而且第一个错误(无法隐式转换...)仍然存在。
那么为什么会出现这个错误,正确的实现方式是什么呢?

5
不可能实现,需要返回一个T。虽然"MyImplementation"是"IMyInterface"的一种实现,但并不是每个"IMyInterface"都会是"MyImplementation"。 - DavidG
1个回答

1
我对泛型有些问题,但是我看不出我的错误。
你的错误在于使用了泛型。根据你展示的代码,你根本不需要使用它们。工厂应该返回一个`IMyInterface`而不是`T`。
public interface IMyFactory
{
    IMyInterface Create();
}

public class MyFactory : IMyFactory
{
    public IMyInterface Create()
    {
        // Complex logic here to determine what i would like to give back
        return new MyImplementation();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接