.NET我想克隆一个值类型的字段。如何使用反射(或其他动态的)在值类型上设置字段值?
这适用于引用类型,但不适用于值类型。我理解为什么,但我不知道另一种选择。
shared function clone(of t)(original as t) as t
dim cloned as t
'if class then execute parameterless constructor
if getType(t).isClass then cloned = reflector.construct(of t)()
dim public_fields = original.getType.getFields()
for each field in public_fields
dim original_value = field.getValue(original)
'this won't work for value type, but it does work for reference type ???
field.setValue(cloned, original_value)
next
return cloned
end function
答案 0 :(得分:2)
如果它是一个值类型,那么你很快完成,只需返回“原始”:
'if class then execute parameterless constructor
If GetType(t).IsClass Then
Dim types(-1) As Type
cloned = DirectCast(GetType(t).GetConstructor(types).Invoke(Nothing), t)
Else
Return original
End If
使这个真正具有通用性会更加困难,类型不必具有无参数构造函数。例如尝试一个字符串。
答案 1 :(得分:0)
由于值类型是按值传递的,因此在对象的副本上调用SetValue
。
如果T
是值类型,则只需编写Return original
即可返回副本。
例如:
If GetType(T).IsValueType Then Return original