fork(1) download
  1. using System;
  2. using System.Reflection;
  3.  
  4. public class Program {
  5. public static void Main() {
  6. var objeto = new Tipo() { x = 1, a = "aaa" };
  7. var objeto2 = ObjectUtil<Tipo>.Clone(objeto);
  8. Console.WriteLine(objeto2.x);
  9. }
  10. }
  11.  
  12. static class ObjectUtil<T> {
  13. public static T Clone(T obj) {
  14. Type type = obj.GetType();
  15. var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  16. var cloned = Activator.CreateInstance(type);
  17. for (int i = 0; i < fields.Length; i++) fields[i].SetValue(cloned, fields[i].GetValue(obj));
  18. return (T)cloned;
  19. }
  20. }
  21.  
  22. class Tipo {
  23. public int x;
  24. public string a;
  25. public TimeZoneInfo t;
  26. }
  27.  
  28. //https://pt.stackoverflow.com/q/177137/101
Success #stdin #stdout 0.03s 16124KB
stdin
Standard input is empty
stdout
1