C# 指定的类型必须是不包含引用的结构

C# 指定的类型必须是不包含引用的结构,c#,.net,exception,structure,memory-mapped-files,C#,.net,Exception,Structure,Memory Mapped Files,我正在尝试使用MemoryMappedViewAccessor类上的Write函数。在这种情况下,我的T如下所示: [StructLayout(LayoutKind.Explicit)] public struct Message { public void AddString(string str) { if (stringContents == null) stringContents =

我正在尝试使用
MemoryMappedViewAccessor
类上的
Write
函数。在这种情况下,我的
T
如下所示:

[StructLayout(LayoutKind.Explicit)]
    public struct Message
    {
        public void AddString(string str)
        {
            if (stringContents == null)
                stringContents = new byte[1024 * 10];
            stringContents = Encoding.ASCII.GetBytes(str);
        }
        public string GetString()
        {
            if (stringContents == null)
                return string.Empty;
            return Encoding.ASCII.GetString(stringContents);
        }
        [FieldOffset(0)]
        public byte[] stringContents;
    }
但是,当我打电话时,例如:

//Initialized Elsewhere: MemoryMappedViewAccessor writer
Message messageAlreadyOnWire = new Message();
messageAlreadyOnWire.AddString(data);
writer.Write<Message>(0, ref messageAlreadyOnWire);
//在别处初始化:MemoryMappedViewAccessor writer
messageAlreadyOnWire=新消息();
messageAlreadyOnWire.AddString(数据);
writer.Write(0,ref messageAlreadyOnWire);
我收到如下错误:

[StructLayout(LayoutKind.Explicit)]
    public struct Message
    {
        public void AddString(string str)
        {
            if (stringContents == null)
                stringContents = new byte[1024 * 10];
            stringContents = Encoding.ASCII.GetBytes(str);
        }
        public string GetString()
        {
            if (stringContents == null)
                return string.Empty;
            return Encoding.ASCII.GetString(stringContents);
        }
        [FieldOffset(0)]
        public byte[] stringContents;
    }
指定的类型必须是不包含引用的结构。 参数名称:类型


我的结构中唯一的“引用”是字节数组。有没有办法解决这个问题?我可以使用固定长度的字节数组,但我不确定如何在不深入研究
不安全的领域的情况下声明一个字节数组,我不希望这样做。

尝试将
[MarshalAs(UnmanagedType.ByValArray,SizeConst=Your_Size)]
应用到
消息中。stringContents
作为解决此问题的一种方法,您可以使用而不是MemoryMappedViewAccessor;然后对其使用常规流读/写,而不是访问器。

建议的属性被添加到代码中。它仍然会产生完全相同的错误:(