开发者

.NET How can i set field value on value type using reflection

开发者 https://www.devze.com 2022-12-23 15:44 出处:网络
.NET I want to clone a value type\'s fields. How can i set a field value on a value type using reflection (or something else dynamically)?

.NET I want to clone a value type's fields. How can i set a field value on a value type using reflection (or something else dynamically)?

This works for reference 开发者_StackOverflow社区types but not for value types. I understand why but I don't know an alternative.

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


If it is a value type then you are done quick, just return "original":

'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

You'll have more trouble making this truly universal, a type doesn't have to have a parameter-less constructor. Try a String for example.


Since value types are passed by value, SetValue is being called on a copy of the object.

If T is a value type, you can simply write Return original and it will return a copy.
For example:

If GetType(T).IsValueType Then Return original
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号