Reflection on structure differs from class - but only in code

前端 未结 4 1852
执笔经年
执笔经年 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条回答
  •  -上瘾入骨i
    2020-12-21 01:53

    Well, you haven't shown all your code - in particular, where you're setting target and how you're checking the value of the field afterwards.

    Here's an example which shows it working fine in C# though:

    using System;
    using System.Reflection;
    
    struct Foo
    {
        public int x;
    }
    
    class Test
    {
        static void Main()
        {
            FieldInfo field = typeof(Foo).GetField("x");
    
            object foo = new Foo();
            field.SetValue(foo, 10);
            Console.WriteLine(((Foo) foo).x);
        }
    }
    

    (I'm pretty sure the choice of language isn't relevant here, but with more code we could tell for certain.) My strong suspicion is that you're doing something like:

    Foo foo = new Foo();
    object target = foo;
    // SetValue stuff
    
    // What do you expect foo.x to be here?
    

    The value of foo in the snippet above won't have changed - because on the second line, the value is copied when it's boxed. You'd need to unbox and copy again afterwards:

    foo = (Foo) target;
    

    If that's not it, please show a short but complete program which demonstrates the problem.

提交回复
热议问题