很抱歉为您提供解释,但这是我所能描述的最好的解释,希望代码对您有所帮助。 (我从类中删除了实现,并重命名以使其尽可能裸露)
当我将接口转换为下面的代码时,出现强制转换异常。反正我可以使它工作吗?
var instance = new Service1() as IService<PocoClass1>; //this works
var instance2 = new Service1() as IService<PocoBase>; // this fails but i want it to work
public abstract class PocoBase
{
public int GetAll()
{
return 0;
}
}
public class PocoClass1: PocoBase
{
}
public interface IService<T> where T : PocoBase
{
void Add(int x);
}
public class Service1 : IService<PocoClass1>
{
public void Add(int x)
{
}
}