我有一些关于泛型的问题,但我找不出我的错误。
给定以下代码:
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 兼容?)而且第一个错误(无法隐式转换...)仍然存在。那么为什么会出现这个错误,正确的实现方式是什么呢?