[英]How to create a clone object in windows 8.1 universal app?
I am migrating my app from Windows Phone 8 to Windows Universal App. 我正在将我的应用程序从Windows Phone 8迁移到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
我曾经对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. 任何人都可以建议,我如何在Windows Universal Apps中实现这一点,因为某些方法如InvokeMemeber不可用。
You need to use the refactored Reflection APIs: 您需要使用重构的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);
}
Error handling omitted for things like missing default constructor etc. 错误处理省略了缺少默认构造函数等的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.