我想创建一个OperationFactory。如果传入一个OperationFactory,则应基于OperationRequest返回一个Operation。
Operation本身具有一个属性,以返回OperationResult。
OperationResult也是通用的。
在我的应用程序看来,我正在获取一些可以创建的信息以及一个OperationRequest。我还要在那里有一个OperationHandler。 OperationHandler将使用OperationsFactory检索正确/所需的操作。
哪个将由OperationHandler执行。
interface IOperationFactory
{
Tout Operation<Tout, TResult, Tin, T>(Tin request)
where Tin : IOperationRequest
where TResult : IOperationResult<T>
where Tout : BaseOperation<T>;
}
interface IOperationHandler
{
IOperationResult<T> Handle<T>(IOperationRequest request);
}
interface IOperationResult<T>
{
Guid Id { get; }
Guid RequestId { get; }
T Value { get; }
}
/* Here's the part that is making my problems, its part of the OperationsFactory: */
public Tout Operation<Tout, TResult, Tin, T>(Tin request)
where Tout : BaseOperation<T>
where TResult : IOperationResult<T>
where Tin : IOperationRequest
{
if (request is AddItemsRequest)
{
var finalType = request as AddItemsRequest;
Type target = typeof(Tout);
return (Tout) new AddItemsOperation(request);
}
throw new InvalidOperationException();
}
public sealed class AddItemsRequest : IOperationRequest
{
public AddItemsRequest(List<Item> items, string site)
{
Id = Guid.NewGuid();
Items = items;
Site = site;
}
public Guid Id { get; }
public List<Item> Items { get; }
public string Site { get; }
}
public sealed class AddItemsOperation : BaseOperation<Tuple<IToken, IBasket>>
{
private readonly IApi _api;
private readonly IToken _token;
public AddItemsOperation(
IOperationRequest request,
)
: this(api, request)
{ }
public AddItemsOperation(Api api, IOperationRequest request)
: base(request)
{
_api = api;
}
public override IOperationResult<Tuple<IToken, IBasket>> Result()
{
/* Implementation Details Removed */
return new OperationResult
<Tuple<IToken, IBasket>>(
Request.Id,
);
}
private AddItemsRequest AddItemsRequest(IOperationRequest request)
{
if (!(request is AddItemsRequest))
{
throw new InvalidOperationException($"Supported type is only {typeof(AddItemsRequest).Name}");
}
return request as AddItemsRequest;
}
无法将类型“ AddItemsRequest”转换为“ Tout”
答案 0 :(得分:0)
您能否尝试以安全的方式返回:
return new AddItemsOperation(
request
) as Tout;