c# 中结构体 的定义字符串字段(性能优化)

张开发
2026/4/16 5:31:56 15 分钟阅读

分享文章

c# 中结构体 的定义字符串字段(性能优化)
在结构体中尽量定义值类型可以通过指针快速读取比如一下示例[StructLayout(LayoutKind.Sequential, Pack 1)] public unsafe struct UseDetail { public const int useName_Size 20; public fixed byte useName[useName_Size]; public string GetUseName() { // 必须 fixed fixed (byte* p useName) { int len 0; while (len useName_Size p[len] ! 0) len; return Encoding.ASCII.GetString(p, len); } } public void SetUserName(string content) { byte[] source Encoding.ASCII.GetBytes(content); // 必须 fixed.NET4.0 强制要求 fixed (byte* pDest useName) { int copyLength Math.Min(source.Length, useName_Size); for (int i 0; i copyLength; i) { pDest[i] source[i]; } } } }快速读写二进制文件public static unsafe class IdStructHelperK8 { /// summary /// 写入结构体到文件 /// /summary public static void WriteStructT(string filePath, T data) where T : struct { int structSize Marshal.SizeOf(typeof(T)); byte[] buffer new byte[structSize]; fixed (byte* p buffer) { *(T*)p data; } File.WriteAllBytes(filePath, buffer); } /// summary /// 从文件读取结构体 /// /summary public static T ReadStructT(string filePath) where T : struct { byte[] buffer File.ReadAllBytes(filePath); fixed (byte* p buffer) { return *(T*)p; } } public static T ReadStructT(byte[] buffer) where T : struct { fixed (byte* p buffer) { return *(T*)p; } } }

更多文章