[英]Cannot return concrete implementation of constraint generic
我在仿制药方面遇到了一些问题,我没有看到我的错误。
鉴于此代码:
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兼容?)并且第一个错误(不能隐式转换...)仍然存在。
那么为什么我会得到这个错误以及返回具体实现的正确实现是什么?
我在仿制药方面遇到了一些问题,我没有看到我的错误。
你的错误是使用泛型。 鉴于您显示的代码,您根本不需要它们。 工厂应返回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.