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

标签 c# generics

我在泛型方面遇到了一些问题,但我没有看到我的错误。

给定这段代码:

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 兼容?)而且第一个错误(无法隐式转换...)仍然存在。

那么为什么我会收到此错误以及返回我的具体实现的正确实现是什么?

最佳答案

I have some problem around generics and I don't see my mistake.

你的错误是使用泛型。鉴于您显示的代码,您根本不需要它们。工厂应该返回一个 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();
    }
}

关于c# - 无法返回约束泛型的具体实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49917261/

相关文章:

c# - 如何从开始到特定条件从通用列表中删除项目

c# - 填充数组以避免索引超出数组错误边界的方法

c# - HTTP Web 请求包装器/帮助器库

c# - 更新面板中的图像导致整个页面刷新

c# - 如何使用 wpf 应用程序在 Twitter 上共享数据或消息?

java - 是否需要在 java 中阐明泛型变量初始化的泛型参数?

swift - 错误 : Generic parameter 'T' could not be inferred.

c# - Azure 突然阻止我访问我的数据库

c# - 对返回类型和参数使用泛型

java - 使用 Java 泛型进行类型强制