我已經定義了一個對象作爲無法賦值給foreach循環中對象的屬性?
public class EmailData
{
public string TemplateId { get; set;}
public IEnumerable<Recipient> To { get; set; }
public IEnumerable<Recipient> CC { get; set; }
public IEnumerable<Recipient> BCC { get; set; }
}
public class Recipient
{
public string Key { get; set; }
public string Type { get; set; }
public string Email { get; set; }
public string Id { get; set; }
}
我有填充在一個構造函數,然後我需要完成填充收件人值,並概括地說:我今(後各種嘗試):
public EmailData EmailObject;
public void BuildEmailData()
{
EmailDataBuilder builder = new EmailDataBuilder(EmailObject,CSGTemplateId);
EmailObject = builder.BuildObject();
}
public void PopulateEmailAddresses()
{
SetToValues();
}
private void SetToValues()
{
foreach (Recipient t in EmailObject.To)
{
var _user = RepoUser.GetUserById(t.Key);
t.Email = _user.Email;
t.Id = _user.Id;
}
}
所以你看到我有一個對象,我需要在它上面填充更多的字段。現在,我得到foreach外觀創建了一個我使用的變量,所以當我分配Email值時,它不是數據參數,而是變量。但我該如何解決這個問題?我是否對foreach錯過了一些簡單的東西?
非常感謝,這是在我意識到作業不能正常工作之前轟炸我的單元測試。
我已經得到了工作,我不喜歡的是使用收件人,而不是直接的IEnumerable的集合:
public class EmailData
{
public string TemplateId { get; set;}
public RecipientCollection To { get; set; }
public RecipientCollection CC { get; set; }
public RecipientCollection BCC { get; set; }
}
public class RecipientCollection: IEnumerable<Recipient>
{
private readonly List<Recipient> variableList = new List<Recipient>();
public IEnumerator<Recipient> GetEnumerator()
{
return variableList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(Recipient v)
{
variableList.Add(v);
}
}
public EmailData BuildObject()
{
// get the template.
EmailObj.TemplateId = _templateRepo.GetCSGEmailTemplate(CSGTemplateId).TemplateId;
// populate the people
RecipientCollection _toCollection = new RecipientCollection();
RecipientCollection _ccCollection = new RecipientCollection();
RecipientCollection _bccCollection = new RecipientCollection();
foreach (var r in _recipRepo.GetRecipientByAction("To"))
{ _toCollection.Add(r); }
EmailObj.To = _toCollection;
foreach (var r in _recipRepo.GetRecipientByAction("CC"))
{ _ccCollection.Add(r); }
EmailObj.CC = _ccCollection;
foreach (var r in _recipRepo.GetRecipientByAction("BCC"))
{ _bccCollection.Add(r); }
EmailObj.BCC = _bccCollection;
return EmailObj;
}
public void BuildEmailData()
{
EmailDataBuilder builder = new EmailDataBuilder(EmailObject,CSGTemplateId);
EmailObject = builder.BuildObject();
}
public void PopulateEmailAddresses()
{
foreach (Recipient t in EmailObject.To)
{
var _user = RepoUser.GetUserById(t.Key);
t.Email = _user.Email;
t.Id = _user.Id;
}
}
這不是理想的,因爲是休息的另一塊本該使用LINQ to XML,但我可以弄清楚。
老實說,我想通過Linq做到這一點,但我似乎無法找到一種方法來分配值。 – BryanGrimes 2010-10-15 16:51:20
嗯......有時候你需要一個普通的舊的for循環而不是foreach,但我沒有一個好的答案。另外,什麼是實際類型?你能暫時停止使用'var'嗎?你需要使用什麼類型的? http://stackoverflow.com/questions/2196638/c-cannot-assign-to-foreach-iteration-variable – 2010-10-15 16:57:06