简体   繁体   English

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

[英]Cannot return concrete implementation of constraint generic

I have some problem around generics and I don't see my mistake. 我在仿制药方面遇到了一些问题,我没有看到我的错误。

Given this code: 鉴于此代码:

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'
    }
}

If I use it like this return new MyImplementation() as T; 如果我像这样使用它return new MyImplementation() as T; it works. 有用。 No more errors are present. 不再存在错误。

If I use it like this return (T)new MyImplementation(); 如果我像这样使用它return (T)new MyImplementation(); i get a code suggestion to remove the unnecessary cast. 我得到一个代码建议删除不必要的演员。 (Yeah that's what I think too, why is it not possible to return the concrete implementation since it is compatible with T?) and also the first error (Cannot implicitly convert...) is still present. (是的,这也是我的想法,为什么不能返回具体的实现,因为它与T兼容?)​​并且第一个错误(不能隐式转换...)仍然存在。

So why do I get this error and what is the correct implementation to return my concrete implementation? 那么为什么我会得到这个错误以及返回具体实现的正确实现是什么?

I have some problem around generics and I don't see my mistake. 我在仿制药方面遇到了一些问题,我没有看到我的错误。

Your mistake is to use generics. 你的错误是使用泛型。 Given the code you shown, you don't need them at all. 鉴于您显示的代码,您根本不需要它们。 The factory should return a IMyInterface instead of T . 工厂应返回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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM