Using a method that accepts Func <T> in the object builder

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 that I can go to Func <> and it will set the correct property for me.

Here is what I still have:

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, WithCategory () works, but I do not 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'm doing wrong?

+4
source share
2 answers

You need to use Action<EquipmentModel> as your argument, not Func<EquipmentModel> .

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

I think that Func<EquipmentModel> points to a function that returns EquipmentModel, so you will need an Action<EquipmentModel> that points to a non-return function that takes the EquipmentModel parameter as a parameter.

+1
source

Source: https://habr.com/ru/post/1344121/


All Articles