Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're on .Net 4, you could use the new <code>Expression</code> types (that were added to support <code>dynamic</code>), to create an expression that assigns the properties, compile it to a delegate once, and call that repeatedly. The performance should be comparable with using Reflection.Emit.</p> <pre><code>class ObjectFiller&lt;T&gt; { private static Func&lt;IDictionary&lt;string, object&gt;, T&gt; FillerDelegate; private static void Init() { var obj = Expression.Parameter(typeof(T), "obj"); var valuesDictionary = Expression.Parameter(typeof(IDictionary&lt;string, object&gt;), "values"); var create = Expression.Assign( obj, Expression.Call(typeof(Activator), "CreateInstance", new[] { typeof(T) })); var properties = typeof(T).GetProperties(); var setters = Expression.Block(properties.Select(p =&gt; CreateSetter(p, obj, valuesDictionary))); var methodBody = Expression.Block(typeof(T), new[] { obj }, create, setters, obj); var fillerExpression = Expression.Lambda&lt;Func&lt;IDictionary&lt;string, object&gt;, T&gt;&gt;(methodBody, valuesDictionary); FillerDelegate = fillerExpression.Compile(); } static Expression CreateSetter(PropertyInfo property, Expression obj, Expression valuesDictionary) { var indexer = Expression.MakeIndex( valuesDictionary, typeof(IDictionary&lt;string, object&gt;).GetProperty("Item", new[] { typeof(string) }), new[] { Expression.Constant(property.Name) }); var setter = Expression.Assign( Expression.Property(obj, property), Expression.Convert(indexer, property.PropertyType)); var valuesContainsProperty = Expression.Call( valuesDictionary, "ContainsKey", null, Expression.Constant(property.Name)); var condition = Expression.IfThen(valuesContainsProperty, setter); return condition; } public T FillObject(IDictionary&lt;string, object&gt; values) { if (FillerDelegate == null) Init(); return FillerDelegate(values); } } </code></pre> <p>You could do something very similar in .Net 3 too, using the <code>Expression</code> version of object initializers.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload