0

I'm using C# to code a basic property/value mapping class.

I want to be able to target a specific member on an object, and then specify various things to do with that member through a lambda expression.

The idea is to construct a new mapping using a static method something like so:

var myMapping = Mapping<TObject>.New(o => o.MyProperty).Read(GetString);

In this example, TObject is the Type of object whose property I want to map, New(...) targets the 'MyProperty' member of the TObject and Read(...) defines an expression which returns a value that is the same type of 'MyProperty'.

So we now have a 'Mapping' object that is aware of:

  1. What member it is associated with.
  2. How to get a value for that member.

We can then leave the logic around how to set that member to that value up to inheritors of 'Mapper'. e.g. a certain type of mapping might want to 'validate' values that are read, only setting MyProperty if they are valid.

You would then use your mapping like so:

myMapping.Read(myTObject);

Where 'myTObject' is an instance of type 'TObject'.

I see implementations of this kind of thing commonly in mocking libraries like RhinoMock, where you can target specific members and set options for them.

Can somebody provide me with an example of how to achieve this, or at least tell me if my head is in the clouds?

Sebastian Nemeth
  • 5,505
  • 4
  • 26
  • 36
  • It's not entirely clear what you want to happen at compile time, and what at execution time. Right now, `var myMapping = (Func)(o => o.MyProperty);` then `var s = myMapping(someTOject);` seem to do what you want? – AakashM Jan 25 '12 at 11:41
  • Is this the sort of thing you need http://stackoverflow.com/questions/8990231/how-can-i-create-a-dynamic-select-on-an-ienumerablet-at-runtime/8990465#8990465 – AlanT Jan 25 '12 at 12:13

1 Answers1

0

Are you talking about Key, Value pairs? Linq already implements the Dictionary<T1, T2> type. The first type is the key and the second the value.

You can do:

Dictionary<TObject, string> myMapping = new Dictionary(TObject, string);

myMapping.Add(new TObject(), "some string");

To read it would be:

string someString = myMapping[tObjectInstance].Value;

You can read more about the dictionary class and how to implement it here: http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

Chuck Savage
  • 11,775
  • 6
  • 49
  • 69