我需要添加到一個ICollection<string>
屬性,其中我有一個IEnumerable
。這裏是一個說明該問題的完整方案:如何在迭代對象類型時添加到ICollection屬性?
using System;
using System.Collections.Generic;
using System.Linq;
namespace CollectionAddingTest
{
public class OppDocumentServiceResult
{
public OppDocumentServiceResult()
{
this.Reasons = new List<string>();
}
public Document Document { get; set; }
public bool CanBeCompleted
{
get
{
return !Reasons.Any();
}
}
public ICollection<string> Reasons { get; private set; }
}
public class Document
{
public virtual string Name { get; set; }
}
public class Program
{
private static void Main(string[] args)
{
var docnames = new List<string>(new[] {"test", "test2"});
var oppDocResult = docnames
.Select(docName
=> new OppDocumentServiceResult
{
Document = new Document { Name = docName }
});
foreach (var result in oppDocResult)
{
result.Document.Name = "works?";
result.Reasons.Add("does not stick");
result.Reasons.Add("still does not stick");
}
foreach (var result in oppDocResult)
{
// doesn't write "works?"
Console.WriteLine(result.Document.Name);
foreach (var reason in result.Reasons)
{
// doesn't even get here
Console.WriteLine("\t{0}", reason);
}
}
}
}
}
我希望每個OppDocumentServiceResult會參考其Document.Name
屬性設置爲作品?和每個OppDocumentServiceResult應該有兩個原因添加到它。但是,兩者都沒有發生。
對於Reasons屬性我有什麼特別之處?
它應該工作絕對好。請提供一個簡短的*完整*程序來證明問題。 –
@JonSkeet修改了上面的要更加完整。清除泥漿? –
不是真的 - 它仍然不是一個簡短但完整的程序,我們可以使用它來確切地確定發生了什麼...... –