我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)
我想链接这些操作,我试图这样做:
var res = await (from x in Op1()
from y in Op2()
from z in Op3()
from w in …
Run Code Online (Sandbox Code Playgroud) 将任务与https://github.com/louthy/language-ext绑定在一起需要返回类型为 ( ) 的任务Task<>
。因此,没有返回类型的任务应转换为Task<Unit>
.
有谁知道在 C# 中使用(或不使用)Language-ExtTask
进行转换的紧凑(仅表达式)方法?Task<Unit>
换句话说:有类似fun(...)
for 的东西Task
吗?
我有以下方法:
private async Task<(bool, string)> Relay(
WorkflowTask workflowTask,
MontageUploadConfig montageData,
File sourceFile,
CancellationToken cancellationToken
)
{
try
{
byte[] fileContent = await _httpClient.GetByteArrayAsync(sourceFile.Url, cancellationToken);
await _attachmentController.TryUploadAttachment(montageData.EventId, fileContent, sourceFile.Name);
return (true, null);
}
catch (Exception exception)
{
_logger.LogError(exception, $"File cannot be uploaded: {sourceFile.Name}", workflowTask);
return (false, exception.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
我想重构它以使用TryAsync
from LanguageExt.Core
(或其他一些功能Try
类型)。
我已成功将上述方法重构为:
private TryAsync<bool> Relay(
MontageUploadConfig montageData,
File sourceFile,
CancellationToken cancellationToken
) => new(async () =>
{
byte[] fileContent = await _httpClient.GetByteArrayAsync(sourceFile.Url, cancellationToken);
return await _attachmentController.TryUploadAttachment(montageData.EventId, …
Run Code Online (Sandbox Code Playgroud) 我正在使用 LanguageExt 来实现 C# 中的函数式编程功能。我有一个方法,我想构建 VaultSharp 实例来访问我们的 HashiCorp Vault 服务。我的目标是通过两个 Either 的链创建 VaultClientSettings 的实例(请参阅下面的方法)。最后,要么从链中的任何 Either 返回异常,要么从 VaultClientSettings 的实例返回异常。我认为我已经很接近了,但无法完成最后一步。我很感激你的建议。
以下是 C# 的 FP 库和 VaultSharp 库的链接;
这是显示我看到的错误的图像:
Either<Exception, Uri> GetVaultUri() =>
EnvironmentVariable.GetEnvironmentVariable(KVaultAddressEnvironmentVariableName)
.Map(uri => new Uri(uri));
Either<Exception, TokenAuthMethodInfo> GetAuthInfo() =>
EnvironmentVariable.GetEnvironmentVariable(KVaultTokenEnvironmentVariableName)
.Map(token => new TokenAuthMethodInfo(token));
Either<Exception, VaultClientSettings> GetVaultClientSettings(
Either<Exception, Uri> vaultUri,
Either<Exception, TokenAuthMethodInfo> authInfo
)
{
/////////////////////////////////////////////////////////////////////////
// I have access to the uri as u and the authmethod as a, but I cannot //
// figure out how …
Run Code Online (Sandbox Code Playgroud)