我在我的应用程序上使用SparkPost向我和客户发送电子邮件.为此,我需要使用C#序列化一个数组.我有以下代码,似乎没有工作,我不知道为什么.
recipients = new List<Recipient>() {
toAddresses.Select(addr => new Recipient() {
address = addr.ToString()
})
}
Run Code Online (Sandbox Code Playgroud)
toAddresses只是一个List<string>电子邮件地址.
收件人类:
class Recipient {
public string address;
}
Run Code Online (Sandbox Code Playgroud)
LINQ select的输出应如下所示:
recipients = new List<Recipient>(){
new Recipient() {
address ="joe_scotto@1.net"
},
new Recipient() {
address ="joe_scotto@2.net"
},
new Recipient() {
address ="joe_scotto@1.net"
},
new Recipient() {
address ="jscotto@2.com"
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助都会很棒,谢谢!
特定错误:
错误CS1503参数1:无法从'System.Collections.Generic.IEnumerable'转换为'app.Recipient'
错误CS1950集合初始化程序的最佳重载Add方法'List.Add(Recipient)'有一些无效的参数
请求字符串:
wc.UploadString("https://api.sparkpost.com/api/v1/transmissions", JsonConvert.SerializeObject(
new {
options = new {
ip_pool = "sa_shared"
},
content = new {
from = new {
name = "a Sports",
email = "no-reply@colorizer.a.com"
},
subject = subject,
html = emailBody
},
recipients = new List<Recipient>() {
toAddresses.Select(addr => new Recipient() {
address => addr
})
}
}
Run Code Online (Sandbox Code Playgroud)
));
好像你需要简单的映射
var recipients = toAddresses.Select(addr => new Recipient { address = addr }).ToList();
Run Code Online (Sandbox Code Playgroud)
您不能将IEnumerable其用作列表初始化的参数
var recipients = new List<Recipient>() { toAddresses.Select... }
Run Code Online (Sandbox Code Playgroud)
初始化逻辑将调用List.Add您传入的每个项目{ },因此它期望Recepient用逗号分隔的实例,但是当您通过IEnumerable它时它会失败.
List<T>有重载构造函数接受IEnumerable<T>作为参数,所以你可以使用它
var recepients = new List<Recepient>(toAddresses.Select(addr => new Recipient {address = addr}));
Run Code Online (Sandbox Code Playgroud)
但就我个人而言,简单的映射似乎更具可读性.
var message = new
{
options = new
{
ip_pool = "sa_shared"
},
content = new
{
from = new
{
name = "a Sports",
email = "no-reply@colorizer.a.com"
},
subject = subject,
html = emailBody
},
recipients = toAddresses.Select(addr => new Recipient() { address = addr}).ToList()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
679 次 |
| 最近记录: |