Information Technology Reference
In-Depth Information
Yo u ' d e x p e c t t h e c o n v e r t e r t o c o p y e v e r y p r o p e r t y f r o m t h e s o u r c e t o t h e
destination where the properties have the same name and the source object
has a public
get
accessor and the destination type has a public
set
acces-
sor. This kind of runtime code generation can be best handled by creating
an expression, and then compiling and executing it. You want to generate
code that does something like this:
// Not legal C#, explanation only
TDest ConvertFromImaginary(TSource source)
{
TDest destination =
new
TDest();
foreach
(
var
prop
in
sharedProperties)
destination.prop = source.prop;
return
destination;
}
Yo u n e e d t o c r e a t e a n e x p r e s s i o n t h a t c r e a t e s c o d e t h a t e x e c u t e s t h e p s e u d o
code written above. Here's the full method to create that expression and
compile it to a function. Immediately following the listing, I'll explain all
the parts of this method in detail. You'll see that while it's a bit thorny at
first, it's nothing you can't handle.
private void
createConverterIfNeeded()
{
if
(converter ==
null
)
{
var
source =
Expression
.Parameter(
typeof
(TSource),
"source"
);
var
dest =
Expression
.Variable(
typeof
(TDest),
"dest"
);
var
assignments =
from
srcProp
in
typeof
(TSource).GetProperties(
BindingFlags
.Public |
BindingFlags
.Instance)
where
srcProp.CanRead
let
destProp =
typeof
(TDest).
GetProperty(
srcProp.Name,
BindingFlags
.Public |
BindingFlags
.Instance)