3
votes

I am migrating my app from Windows Phone 8 to Windows Universal App. My requirement is to create a clone object from existing object. I used to do the same with below code in Windows Phone 8

public static object CloneObject(object o)
    {
        Type t = o.GetType();
        PropertyInfo[] properties = t.GetProperties();

        Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance,
            null, o, null);

        foreach (PropertyInfo pi in properties)
        {
            if (pi.CanWrite)
            {
                pi.SetValue(p, pi.GetValue(o, null), null);
            }
        }

        return p;
    } 

Can anyone suggest, how can I achieve this in Windows Universal Apps, as some methods like InvokeMemeber are not available.

1

1 Answers

1
votes

You need to use the refactored Reflection APIs:

using System.Reflection;

public class Test
{
  public string Name { get; set; }
  public int Id { get; set; }
}

void DoClone()
{
  var o = new Test { Name = "Fred", Id = 42 };

  Type t = o.GetType();
  var properties = t.GetTypeInfo().DeclaredProperties;
  var p = t.GetTypeInfo().DeclaredConstructors.FirstOrDefault().Invoke(null);

  foreach (PropertyInfo pi in properties)
  {
    if (pi.CanWrite)
      pi.SetValue(p, pi.GetValue(o, null), null);
  }

  dynamic x = p;
  // Important: Can't use dynamic objects inside WriteLine call
  // So have to create temporary string
  String s = x.Name + ": " + x.Id;
  Debug.WriteLine(s);
}

Error handling omitted for things like missing default constructor etc.