复制反射的泛型类型值



好吧,所以我有一个通用的复制方法。

在我的类中,我有一个名为GenericPrimitiveContainer的类 - 它只保存T值。

在我的通用复制方法中,我想将值从实例 A 复制到实例 B。

到目前为止,它看起来像这样:

var instance = Activator.CreateInstance(props[i].PropertyType);
var container = props[i].GetValue(source, null);

这些为我提供了新实例(实例(和我正在从中复制的实例(容器(。

我可以这样说:

(instance as GenericPrimitiveContainer<int>).Value = (container as GenericPrimitiveContainer<int>).Value;

但这不是很通用。如果我删除"int",那么它会告诉我"预期类型",如果我删除尖括号,它也不会起作用。

我知道我想要的类型,并且该类型位于称为 genericArgs 的 Type[] 中。但是如果我放在那里,它也行不通。

我该怎么做?

我的建议是以下方法:

private T Copy<T>(T original)
{
Type type = original.GetType();
var copy = Activator.CreateInstance<T>();
var props = type.GetProperties();           
foreach (var prop in props)
{
// Get the value of the original objects property
var originalPropertyValue = prop.GetValue(original, null);
// Set the value to the new objects property
prop.SetValue(copy, originalPropertyValue);
}
return copy;
}

最新更新