This is mostly for educational purposes. I’m trying to create the InputMapper class, which is used in this example:
var mapper = new InputMapper<SomeType>();
mapper.Map("some user input", someType => someType.IntProperty, "Input was not an integer");
mapper.Map("some user input", someType => someType.BoolProperty, "Input was not a bool");
SomeType someTypeInstance = mapper.CreateInstance();
My InputMapper class holds a collection of all of the mappings created using the Map() method. CreateInstance() will loop through the mappings trying to convert the user input and assign it to the property used in the lambda expression. As it loops through, it will save a collection of any FormatExceptions that are thrown.
My questions are:
- In the InputMapper.Map() method, what should the lambda parameter type be?
- In the InputMapper.CreateInstance() method, how do I go about trying to set the properties on the instance of T that I have created?
Thanks!
Update
Dr. Skeet asked for some more information about my intentions.
The InputMapper class will be used to assign user input to the members of any object, taking care of the conversion of the user input to the properties type. The interface of the class can be inferred from the example above.
Update 2
After some hand holding, Jon and Dan, got me there. Can you suggest improvements? Here’s what I have: http://pastebin.com/RaYG5n2h
For your first question, the
Mapmethod should probably be generic. For example:Now it’s worth noting that your lambda expressions represent the property getters, but presumably you want to call the property setters. That means your code won’t be compile-time safe – there could be a mapped property which is read-only, for example. Also, there’s nothing to restrict the lambda expression to only refer to a property. It could do anything. You’d have to put in execution-time guards against that.
Once you have found the property setters though, you just need to create an instance of
TSourceusingnew TSource()(note the constructor constraint onTSourceabove) and then perform the appropriate conversions and call the property setters.Without more details on what you’re trying to do, I’m afraid it’s not terribly easy to give a more detailed answer.
EDIT: The code to work out the property would look something like this: