如何在Windows 8.1通用应用程序中创建克隆对象?

时间:2015-04-08 15:51:41

标签: c# win-universal-app

我正在将我的应用从Windows Phone 8迁移到Windows Universal App。我的要求是从现有对象创建克隆对象。我曾经对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;
    } 

任何人都可以建议,我如何在Windows Universal Apps中实现这一点,因为某些方法(例如InvokeMemeber)不可用。

1 个答案:

答案 0 :(得分:1)

您需要使用重构的Reflection API:

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);
}

省略了缺少默认构造函数等的错误处理。