我正在尝试将多个字符串添加到C#中的MailAddress。
如果我使用ForEach,我的代码将如下所示
foreach (var item in GetPeopleList())
{
m.Bcc.Add(new MailAddress(item.EmailAddress));
}我现在正试着用我的foreach (即List.ForEach())来做这件事,但是我做不到。
public class Person
{
public Person(string firstName, string lastName, string emailAddress)
{
FirstName = firstName;
LastName = lastName;
EmailAddress = emailAddress;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
}
static void Main(string[] args)
{
MailMessage m = new MailMessage();
List<Person> people = GetPeopleList();
m.Bcc.Add(people.ForEach(Person people =>
{
//what goes here?
}
));
}
private static List<Person> GetPeopleList()
{
List<Person> peopleList = new List<Person>();
//add each person, of type Person, to the list and instantiate the class (with the use of 'new')
peopleList.Add(new Person("Joe", "Bloggs", "Joe.Bloggs@foo.bar"));
peopleList.Add(new Person("John", "Smith", "John.Smith@foo.bar"));
peopleList.Add(new Person("Ann", "Other", "Ann.Other@foo.bar"));
return peopleList;
}我已经尝试了这个的几个版本/变体,但我显然做错了什么。我在Eric Lippert's page上读到了这一点,遗憾的是,这也没有帮助。
发布于 2013-02-25 22:04:27
你需要像这样的东西
people.ForEach(Person p => {
m.Bcc.Add(new MailAddress(p.EmailAddress));
});您将在列表中添加单个项目ForEach person,而不是添加使用ForEach选择的单个项目范围。
也就是说..。我自己更喜欢常规的foreach循环。
发布于 2013-02-25 22:05:18
直接引用自博客:
第二个原因是,这样做不会给语言增加任何新的表示能力。这样做可以让你重写这段清晰的代码:
foreach(Foo foo in foos){涉及foo的语句;}
到下面的代码中:
foos.ForEach((Foo foo)=>{涉及foo的语句;});
它使用几乎完全相同的字符,但顺序略有不同。然而,第二个版本更难理解,更难调试,并且引入了闭包语义,从而以微妙的方式潜在地改变了对象的生命周期。
Eric Lippert明确呼吁不要这么做。
发布于 2013-02-25 22:07:05
试一试
people.ForEach(Person person =>
{
m.Bcc.Add(new MailAddress(person.EmailAddress));
});https://stackoverflow.com/questions/15068742
复制相似问题