Mat*_*att 6 c# generics generic-constraints
我在使这个通用约束工作时遇到了一些麻烦.
我有两个接口.
我希望能够将ICommandHandlers TResult类型限制为仅使用实现ICommandResult的类型,但ICommandResult有自己需要提供的约束.ICommandResult可能会从其Result属性返回值或引用类型.我错过了一些明显的东西吗 谢谢.
public interface ICommandResult<out TResult>
{
TResult Result { get; }
}
public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand
where TResult : ICommandResult<????>
{
TResult Execute( TCommand command );
}
Run Code Online (Sandbox Code Playgroud)
您可以将界面更改为此(对我来说看起来更干净):
public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand
{
ICommandResult<TResult> Execute( TCommand command );
}
Run Code Online (Sandbox Code Playgroud)
或者您可以将类型参数添加ICommandResult<TResult>
到通用参数列表中:
public interface ICommandHandler<in TCommand, TCommandResult, TResult>
where TCommand : ICommand
where TCommandResult: ICommandResult<TResult>
{
TCommandResult Execute( TCommand command );
}
Run Code Online (Sandbox Code Playgroud)