Sdílet prostřednictvím


blambert/codesnip – Copy public properties between two objects implementing the same interface.

You have some interface, IFoo.

It is implemented by two concrete classes:

  • Foo : IFoo (what you expose to the outside world)
  • FooEntity : IFoo (what you store someplace; it’s a superset of Foo, which implements, IFoo)

And you want a simple way to copy the IFoo properties from one IFoo object, to another IFoo object, bidirectionally.

Here it is:

 using System.Reflection;

 public static class Reflection
{
    /// <summary>
    /// Copies all the public instance properties from the source object to the destination object, for the specified type.
    /// </summary>
    /// <typeparam name="T">The type of the operation.</typeparam>
    /// <param name="source">The source object.</param>
    /// <param name="destination">The destination object.</param>
    public static void CopyPublicInstanceProperties<T>(T source, T destination)
    {   
        foreach (PropertyInfo propertyInfo in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            propertyInfo.GetSetMethod().Invoke(destination, new object[] { propertyInfo.GetGetMethod().Invoke(source, null) });
        }
    }        
}

 Where T is an interface (in this case, IFoo) that both objects implement.
 Here’s an example:
 Reflection.CopyPublicInstanceProperties<IFoo>(foo, fooEntity);

Best!

Brian

Comments