我正在为C#使用Language-Ext库,我正在尝试链接返回Either
类型的异步操作。假设我有三个函数,如果它们成功则返回一个整数,如果失败则返回一个字符串,另一个函数将前三个函数的结果相加。在下面的示例实现中,Op3
失败并返回一个字符串。
public static async Task<Either<string, int>> Op1()
{
return await Task.FromResult(1);
}
public static async Task<Either<string, int>> Op2()
{
return await Task.FromResult(2);
}
public static async Task<Either<string, int>> Op3()
{
return await Task.FromResult("error");
}
public static async Task<Either<string, int>> Calculate(int x, int y, int z)
{
return await Task.FromResult(x + y + z);
}
我想链接这些操作,我试图这样做:
var res = await (from x in Op1()
from y in Op2()
from z in Op3()
from w in Calculate(x, y, z)
select w);
但是我们代码没有编译,因为我得到了cannot convert from 'LanguageExt.Either<string, int>' to 'int'
的参数的错误Calculate
。我应该如何链接这些功能?
答案 0 :(得分:2)
问题在于LINQ查询无法计算出要使用的SelectMany
版本,因为第二行未使用x
。您可以通过将Task<Either<L, R>>
转换为EitherAsync<L, R>
来解决此问题:
public static async Task<int> M()
{
var res = from x in Op1().ToAsync()
from y in Op2().ToAsync()
from z in Op3().ToAsync()
from w in Calculate(x, y, z).ToAsync()
select w;
return await res.IfLeft(0);
}
或者,不返回Task<Either<L, R>>
,而是返回EitherAsync<L, R>
:
public static EitherAsync<string, int> Op1() =>
1;
public static EitherAsync<string, int> Op2() =>
2;
public static EitherAsync<string, int> Op3() =>
3;
public static EitherAsync<string, int> Calculate(int x, int y, int z) =>
x + y + z;
public static async Task<int> M()
{
var res = from x in Op1()
from y in Op2()
from z in Op3()
from w in Calculate(x, y, z)
select w;
return await res.IfLeft(0);
}
答案 1 :(得分:0)
x,y和z不是int类型,而是Either<string, int>
更改Calculate(int x, int y, int z)
以接受任一调用的实例:Calculate(Either<string, int> x, Either<string, int> y, Either<string, int>z)
或传递
x.{The int getter property}