0

为什么这会给我一个编译时错误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(); 
}
4

2 回答 2

4

这种转换是不安全的,因为您可以提供与ListCompetitionsfor不同的通用参数TOperation,例如,您可以:

public class OtherOperation : IOperation { }
OtherOperation op = GetOperation<OtherOperation>();

如果编译器允许您的方法,这将在运行时失败。

您可以添加一个新的约束,例如

public TOperation GetOperation<TOperation>() where TOperation : IOperation, new()
{
    return new TOperation();
}

或者,您可以将返回类型更改为IOperation

public IOperation GetOperation()
{
    return new ListCompetitions();
}

从您的示例中不清楚在这种情况下使用泛型有什么好处。

于 2013-03-23T13:39:13.303 回答
1

因为TOperation可能是任何实现的东西IOperation,你不能确定它ListCompetitions是一个TOperation.

您可能想要返回一个 IOperation:

public IOperation GetOperation<TOperation>() where TOperation : IOperation
{
    return new ListCompetitions(); 
}
于 2013-03-23T13:39:22.003 回答