Advertisement
Guest User

Untitled

a guest
Jan 19th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.08 KB | None | 0 0
  1. using System.Reflection;
  2.  
  3. namespace DnDShared.Models.DTOs
  4. {
  5.     public class DTO<T> where T : DTO<T>, new()
  6.     {
  7.         public static T CreateFrom(object Source)
  8.         {
  9.             MethodInfo FactoryFactory = typeof(DTO<>).GetMethod("CreateFrom");
  10.             T Output = new T();
  11.  
  12.             foreach(var Property in typeof(T).GetProperties())
  13.             {
  14.                 PropertyInfo SourceType = Source.GetType().GetProperty(Property.Name);
  15.                 if (SourceType != null)
  16.                 {
  17.                     if (Property.PropertyType == SourceType.PropertyType)
  18.                     {
  19.                         Property.SetValue(Output, SourceType.GetValue(Source));
  20.                     }
  21.                     else if(Property.PropertyType.IsSubclassOf(typeof(DTO<>)))
  22.                     {
  23.                         Property.SetValue(Output, FactoryFactory.MakeGenericMethod(new[] { Property.PropertyType }).Invoke(null, new[] { SourceType.GetValue(Source) }));
  24.                     }
  25.                 }
  26.             }
  27.             return null;
  28.         }
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement