使用采用 Func的方法在对象生成器上
我正在尝试创建一个对象生成器,以便我可以轻松地创建用于单元测试的对象。我想创建一个 With() 方法,这样我就可以传入一个 Func<>它将为我设置正确的属性。
这是我到目前为止所拥有的:
public class EquipmentModelBuilder
{
public EquipmentModel Object { get; set; }
public EquipmentModelBuilder()
{
Object = new EquipmentModel();
}
public EquipmentModelBuilder WithCategory(int categoryId)
{
Object.EquipmentCategoryID = categoryId;
return this;
}
public EquipmentModelBuilder With(Func<EquipmentModel> setter)
{
Object = setter.Invoke();
return this;
}
public EquipmentModel Build()
{
return Object;
}
}
当然,WithCategory() 可以工作,但我不想为每个属性创建所有方法,我希望能够:
EquipmentModelBuilder.With(x => x.Property1 = 1).With(x => x.Property2 = "2").Build()
知道我做错了什么吗?
I am trying to create an Object Builder so I can easily create objects for unit testing. I would like to create a With() method so I can pass in a Func<> and it will set the correct property for me.
Here is what I have so far:
public class EquipmentModelBuilder
{
public EquipmentModel Object { get; set; }
public EquipmentModelBuilder()
{
Object = new EquipmentModel();
}
public EquipmentModelBuilder WithCategory(int categoryId)
{
Object.EquipmentCategoryID = categoryId;
return this;
}
public EquipmentModelBuilder With(Func<EquipmentModel> setter)
{
Object = setter.Invoke();
return this;
}
public EquipmentModel Build()
{
return Object;
}
}
Of course, the WithCategory() works, but I don't want to create all the methods for each property, I would like to be able to:
EquipmentModelBuilder.With(x => x.Property1 = 1).With(x => x.Property2 = "2").Build()
Any idea what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
Action
作为参数,而不是Func
。You need to use an
Action<EquipmentModel>
as your argument rather than aFunc<EquipmentModel>
.我认为
Func
指定了一个返回 EquipmentModel 的函数,因此您需要的是一个Action
,它指定一个不返回且接受的函数EquipmentModel 作为参数。I think that
Func<EquipmentModel>
is specifying a function that returns an EquipmentModel, so what you would want is anAction<EquipmentModel>
which specifies a function with no return that accepts an EquipmentModel as parameter.