Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using reflection in and of itself is not bad, but you will take a performance hit especially if you do it recursively.</p> <p>I am not a fan of the hard coded copy constructors either because developers forget to update them when they add new properties to a class.</p> <p>There are other ways of accomplishing what you want, including Marc Gravells <a href="http://www.codeproject.com/KB/cs/HyperPropertyDescriptor.aspx" rel="nofollow noreferrer">Hyper Property Descriptor</a> or if you want to learn some IL and OPCodes you can use System.Reflection.Emit or even <a href="http://www.mono-project.com/Cecil" rel="nofollow noreferrer">Cecil from Mono</a>.</p> <p>Here's an example of using Hyper Property Descriptor that you can possibly tailor to your needs:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using Hyper.ComponentModel; namespace Test { class Person { public int Id { get; set; } public string Name { get; set; } } class Program { static void Main() { HyperTypeDescriptionProvider.Add(typeof(Person)); var properties = new Dictionary&lt;string, object&gt; { { "Id", 10 }, { "Name", "Fred Flintstone" } }; Person person = new Person(); DynamicUpdate(person, properties); Console.WriteLine("Id: {0}; Name: {1}", person.Id, person.Name); Console.ReadKey(); } public static void DynamicUpdate&lt;T&gt;(T entity, Dictionary&lt;string, object&gt; { foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(typeof(T))) if (properties.ContainsKey(propertyDescriptor.Name)) propertyDescriptor.SetValue(entity, properties[propertyDescriptor.Name]); } } } </code></pre> <p>If you decide to carry on using reflection, you can reduce the performance hit by caching your calls to GetProperties() like so:</p> <pre><code>public Foo(IFoo other) { foreach (var property in MyCacheProvider.GetProperties&lt;IFoo&gt;()) property.SetValue(this, property.GetValue(other, null), null); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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