Reflection on structure differs from class - but only in code

前端 未结 4 1860
执笔经年
执笔经年 2020-12-21 01:11

Code snippet:

Dim target As Object
\' target gets properly set to something of the desired type
Dim field As FieldInfo = target.GetType.GetField(\"fieldName\         


        
4条回答
  •  心在旅途
    2020-12-21 01:58

    Working with your original sample, I agree that it works in C# but not in VB! If you use Reflector or ILDasm you will see that the call to Field.SetValue(target, ...) is actually compiled (in VB) as:

    field.SetValue(RuntimeHelpers.GetObjectValue(target), ...)
    

    GetObjectValue "Returns a boxed copy of obj if it is a value class; otherwise obj itself is returned." I.e. the value is being set on a copy of your struct!

    This link gives the explanation (such as it is). The workaround is to declare target as System.ValueType instead of Object. I'm not sure if that actually helps in your real-life code: you may need a messy type test to be able to handle value types separately from reference types.

提交回复
热议问题