我试图在结构字段上使用 Reflection.FieldInfo.SetValue 来修改其值,但无济于事为什么? 提供了 C# 和 VB 中的代码

问题描述

我正在尝试使用 Reflection.FieldInfo.SetValue修改结构的整数字段值。但是,它不会被修改

我意识到,SetValue 需要一个对象,但装箱整数也无济于事。

我的错误是什么?

这里已经准备好在 C# 中复制和粘贴代码(在 VB 中更进一步):

using System;
using System.Reflection;

public static class Test
{
    public struct sstruct
    {
        public int Value;
    }

    public static void Main()
    {
        // Initialize a structure record.
        sstruct rStruct = new sstruct();
        rStruct.Value = 42;

        // Reading the Value field by name:
        Type tStruct = typeof(sstruct);
        FieldInfo fValue = tStruct.GetField("Value");
        object ovalue = fValue.GetValue(rStruct);
        Console.WriteLine("Read Value Before Mod: {0}",ovalue);

        // Attempting to modify the Value field:
        fValue.SetValue(rStruct,21);
        ovalue = fValue.GetValue(rStruct);
        Console.WriteLine("Read Value After Mod:  {0}",ovalue);
        // It didn't change.

        // SetValue is expecting an object though. Box the struct.
        object oStruct = rStruct;
        fValue.SetValue(oStruct,21);
        ovalue = fValue.GetValue(rStruct);
        Console.WriteLine("Read After Boxing:     {0}",ovalue);
        // It didn't change.

        Console.Read();
    }
}

这里是 VB:

Imports System
Imports System.Reflection

Module Test
    Public Structure sstruct
        Public Value As Integer
    End Structure

    Public Sub Main()
        'Initialize a structure record.
        Dim rStruct As New sstruct
        rStruct.Value = 42

        'Reading the Value field by name:
        Dim tStruct As Type = GetType(sstruct)
        Dim fValue As FieldInfo = tStruct.GetField("Value")
        Dim ovalue As Object = fValue.GetValue(rStruct)
        Console.WriteLine("Read Value Before Mod: {0}",ovalue)

        'Attempting to modify the Value field:
        fValue.SetValue(rStruct,21)
        ovalue = fValue.GetValue(rStruct)
        Console.WriteLine("Read Value After Mod:  {0}",ovalue)
        'It didn't change.

        'SetValue is expecting an object though. Box the struct.
        Dim oStruct As Object = rStruct
        fValue.SetValue(oStruct,21)
        ovalue = fValue.GetValue(rStruct)
        Console.WriteLine("Read After Boxing:     {0}",ovalue)
        'It didn't change.

        Console.Read()
    End Sub
End Module

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)