TypeReference 和 FieldInfo.SetValueDirect 不是持久性的

本文关键字:持久性 SetValueDirect FieldInfo TypeReference | 更新日期: 2023-09-27 18:37:10

我正在使用TypedReference在结构中设置一个值,其中包含FieldInfo.SetValueDirect(TypedReference的实际用途)。

总体目标是拥有一个通用的结构到缓冲区和缓冲区到结构函数,该函数将读取 TCP 数据流直接进入 C 样式结构(C# 中的位字段)。

感谢一些很棒的帖子,到目前为止,我已经为我的目的工作了,但我找不到使TypeReference工作的方法。

此代码是项目的剥离版本,用于说明最后一个问题:结构被正确填充使用 FieldInfo.SetValueDirect() 从缓冲区中,但当我离开例程时它会失去范围。

    public class structL4
    {
        public UInt16 Label;
    }
    static class StructConvert
    {
        public static void BufferToStruct<T>(byte[] buffer, int offset, T t) where T : struct
        {
            UInt16 val;
            foreach (System.Reflection.FieldInfo f in t.GetType().GetFields())
            {
                val = BitConverter.ToUint16(buffer,offset);
                TypedReference reference = __makeref(t);
                f.SetValueDirect(reference, val); // t.Label now contains the right value but is lost
            }
        }
        public static void StructToBuffer<T>(T t, byte[] buffer, int offset) where T : struct
        {
            UInt16 val;
            foreach (System.Reflection.FieldInfo f in t.GetType().GetFields())
            {
                val = (UInt16)f.GetValue(t);
                Array.Copy(BitConverter.GetBytes(val), 0, buffer, offset, sizeof(UInt16));
            }
        }
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        structL4 L0 = new structL4();
        structL4 L1 = new structL4();
        byte[] buffer = new byte[4];
        L0.Label = 0x8C54;
        StructConvert.StructToBuffer(L0, buffer, 0);  // works
        StructConvert.BufferToStruct(buffer,0,L1);    // does not work.
    }

我希望 BufferToStruct() 通过引用对传递的结构进行操作,这样我就不必分配它,但我找不到编译器满意的解决方案。

总的来说,这个想法工作得很好,至少对于 StructToBuffer(),我将与数十个按位 C 类型结构一起使用。

我对TypeReference和FieldInfo方法有点不满意;只使用C#很短的时间。任何帮助非常感谢!

TypeReference 和 FieldInfo.SetValueDirect 不是持久性的

由于默认情况下会复制"值类型"并将副本传递到方法中,因此不会修改实际结构。

您可以返回一个结构并分配它,或者通过 ref 传递结构。

public static void BufferToStruct<T>(byte[] buffer, int offset, ref T t) where T : struct//Note the ref modifier

然后称其为

StructConvert.BufferToStruct(buffer,0,ref L1);