我在泛型方面遇到了一些问题,但我没有看到我的错误。
给定这段代码:
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/