【发布时间】:2020-12-22 18:01:02
【问题描述】:
如何在 C# 中实现 Dictionary 类型和对象数组之间的三元运算符?
我尝试了以下,但给了我错误:
System.Collections.Generic.IEnumerable<System.Collections.Generic.Dictionary<string, string>>" and "object[]
public async Task NovoEmail(Escrita.Email email)
{
try
{
var response = await $"{_configuration["MicrosoftGraph:Url"]}/users/{email.Remetente}/sendMail"
.WithOAuthBearerToken(await _graph.Token())
.PostJsonAsync(new
{
message = new
{
subject = email.Assunto,
body = new { contentType = "HTML", content = email.Corpo },
toRecipients = email.Destinatarios.Select(destinatario => new { emailAddress = new { address = destinatario } }),
ccRecipients = email.Copias.Select(copia => new { emailAddress = new { address = copia } }),
attachments = email.Anexos.Count > 0 ? email.Anexos.Select(anexo => new Dictionary<string, string> {
{ "@odata.type", "#microsoft.graph.fileAttachment" },
{ "name", anexo.FileName },
{ "contentType", anexo.ContentType },
{ "contentBytes", _base64.FormFileToBase64(anexo) }
}) : new object[] { }
}
});
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
throw ex;
}
}
【问题讨论】:
-
如果你使用
new Dictionary<string, string>()会怎样? (或null) -
代替这个
new object[]使用new Dictionary<string, string>() -
如果有多个
Anexos,我认为你的代码会抛出An item with the same key has already been added.的运行时异常 -
你为什么还要测试
>0?如果没有项目,email.Anexos.Select(...)将返回一个空枚举。如果您确实需要它,那么您需要匹配Enumerable.Empty<Dictionary<string,string>>()以匹配Select。 -
@IanMercer 同意,这似乎不需要。如果有人坚持,我也会联系
Enumerable.Empty<IDictionary<string,string>>()。