作为对字符串不变性(https://stackoverflow.com/a/37253663/6619353)的好答案的后续,我已经开始尝试使用这种技术来理解可修改字节的偏移量。
最后,我发现对两个引用字段使用[FieldOffset(0)]
不会使指针具有相同的值。
这是测试:
using System;
using System.Runtime.InteropServices;
namespace ConsoleApp
{
[StructLayout(LayoutKind.Explicit)]
public struct MutableString
{
[FieldOffset(0)]
public readonly string AsString;
[FieldOffset(0)]
public readonly char[] AsCharArray;
public MutableString(string original)
{
AsCharArray = null;
AsString = original;
}
}
public static class Program
{
public static unsafe void Main(string[] args)
{
var mutableString = new MutableString("test");
fixed (char* pString = mutableString.AsString,pcharArray = mutableString.AsCharArray)
{
Console.WriteLine((long)pString); // 2229380919860
Console.WriteLine((long)pcharArray); // 2229380919864
}
}
}
}
上面的代码显示不同的数字(确切的值有时会有所不同)。
差异始终为4个字节(2个字符)。
这是csproj文件:
<Project Sdk="microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp2.0;net47</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
</Project>
.NET Core dll和net47 exe,调试/发布,x86 / x64构建配置的行为相同。
主机是Win10 x64。
我想知道在仅分配AsString
字段之后,如何在具有相同偏移量的字段中得到另一个值?