【发布时间】:2013-03-24 12:21:22
【问题描述】:
为什么这会给我一个编译时错误Cannot convert 'ListCompetitions' to 'TOperation':
public class ListCompetitions : IOperation
{
}
public TOperation GetOperation<TOperation>() where TOperation : IOperation
{
return (TOperation)new ListCompetitions();
}
然而这是完全合法的:
public TOperation GetOperation<TOperation>() where TOperation : IOperation
{
return (TOperation)(IOperation)new ListCompetitions();
}
【问题讨论】:
-
长颈鹿是一种动物。格里是一只长颈鹿。在下一句中,“T”可以替换为任何一种动物。长颈鹿格里是个T。现在你看到问题了吗?使该句子成立的 T 的唯一有效值是“giraffe”和“animal”,但 T 可以是任何种动物。
-
感谢 Eric,这是有道理的(尽管我认为它仍然可能是运行时错误,而不是编译器错误,尽管我确信你们以这种方式实现它有更深层次的原因这让我望而却步..)
标签: c# .net generics interface