使用采用 Func的方法在对象生成器上

发布于 2024-10-23 23:13:19 字数 863 浏览 2 评论 0原文

我正在尝试创建一个对象生成器,以便我可以轻松地创建用于单元测试的对象。我想创建一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光沙漏 2024-10-30 23:13:19

您需要使用 Action 作为参数,而不是 Func

public EquipmentModelBuilder With(Action<EquipmentModel> setter)
{
    setter.Invoke(this.Object);
    return this;
}

You need to use an Action<EquipmentModel> as your argument rather than a Func<EquipmentModel>.

public EquipmentModelBuilder With(Action<EquipmentModel> setter)
{
    setter.Invoke(this.Object);
    return this;
}
千年*琉璃梦 2024-10-30 23:13:19

我认为 Func 指定了一个返回 EquipmentModel 的函数,因此您需要的是一个 Action ,它指定一个不返回且接受的函数EquipmentModel 作为参数。

I think that Func<EquipmentModel> is specifying a function that returns an EquipmentModel, so what you would want is an Action<EquipmentModel> which specifies a function with no return that accepts an EquipmentModel as parameter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文