在这里查看帖子时,看起来我应该能够使用 创建多个对象CreateMany()
,使用 迭代它们foreach
,然后将它们作为数组返回。
我所看到的是每次迭代似乎每次都创建新对象。这是预期的行为吗?
要创建的实体:
public class TestEntity
{
public int Id { get; private set; }
public string SomeString { get; set; }
public void SetId(int value)
{
this.Id = value;
}
}
示例程序.cs:
private static int id;
static void Main(string[] args)
{
var fixture = new Fixture();
IEnumerable<TestEntity> testEntities =
fixture.Build<TestEntity>().CreateMany(5);
Output(testEntities);
foreach (var testEntity in testEntities)
{
testEntity.SetId(id++);
Console.WriteLine(
string.Format("CHANGED IN FOREACH:: hash: {0}, id: {1}, string: {2}",
testEntity.GetHashCode(), testEntity.Id, testEntity.SomeString));
}
Output(testEntities);
}
private static void Output(IEnumerable<TestEntity> testEntities)
{
foreach (var testEntity in testEntities)
{
Console.WriteLine(
string.Format("hash: {0}, id: {1}, string: {2}",
testEntity.GetHashCode(), testEntity.Id, testEntity.SomeString));
}
}
我在这里创建了一个问题(如果这是预期的行为,可能会被删除)。
编辑 2011-06-02
要获得我所期望的行为,并且如果我不想修改 AutoFixture 行为,我可以使用扩展方法:
var fixture = new Fixture();
TestEntity[] testEntities = fixture.Build<TestEntity>().CreateMany(5).ToArray();