如何解决我试图在结构字段上使用 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 举报,一经查实,本站将立刻删除。