Tag: structlayout

为什么System.DateTime结构具有布局类型Auto?

struct System.DateTime及其表兄System.DateTimeOffset的结构布局类型设置为“Auto”。 这可以通过以下方式看出: typeof(DateTime).IsAutoLayout /* true */ 要么: typeof(DateTime).StructLayoutAttribute.Value /* Auto */ 或者可以从IL中看到它声明: .class public auto ansi serializable sealed beforefieldinit System.DateTime ¯¯¯¯ 通常,使用C#编写的struct(不是枚举的.NET值类型)将具有“Sequential”布局(除非已应用StructLayoutAttribute来指定另一个布局)。 我搜索了一些常见的BCL程序集, DateTime和DateTimeOffset是我在这个布局中找到的唯一公开可见的结构。 有谁知道为什么DateTime有这个不寻常的结构布局?

C#StructLayout.Explicit问题

我试图理解为什么下面的第二个例子没有问题,但第一个例子给了我下面的例外。 在我看来,两个例子都应该基于描述给出例外。 任何人都可以开导我吗? 未处理的exception:System.TypeLoadException:无法从程序集’StructTest,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null’加载类型’StructTest.OuterType’,因为它包含偏移0处的对象字段,该字段未正确对齐或重叠由非对象字段。 在StructTest.Program.Main(String [] args)按任意键继续。 。 。 例1 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace StructTest { [StructLayout(LayoutKind.Sequential, Pack = 1)] struct InnerType { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)] char[] buffer; } [StructLayout(LayoutKind.Explicit)] struct OuterType { [FieldOffset(0)] int someValue; [FieldOffset(0)] InnerType someOtherValue; } class […]

应该更改像这样的字符串的内容会导致exception吗?

请考虑以下代码: using System; using System.Runtime.InteropServices; namespace Demo { class Program { static void Main(string[] args) { const string test = “ABCDEF”; // Strings are immutable, right? char[] chars = new StringToChar{str=test}.chr; chars[0] = ‘X’; // On an x32 release or debug build or on an x64 debug build, // the following prints “XBCDEF”. // On […]

当子结构具有LayoutKind.Explicit时,不遵循LayoutKind.Sequential

运行此代码时: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace StructLayoutTest { class Program { unsafe static void Main() { Console.WriteLine(IntPtr.Size); Console.WriteLine(); Sequential s = new Sequential(); sA = 2; sB = 3; s.Bool = true; s.Long = 6; sCInt32a = 4; sCInt32b = 5; int* ptr = (int*)&s; Console.WriteLine(ptr[0]); Console.WriteLine(ptr[1]); Console.WriteLine(ptr[2]); Console.WriteLine(ptr[3]); […]

如果struct包含DateTime字段,为什么LayoutKind.Sequential的工作方式不同?

如果struct包含DateTime字段,为什么LayoutKind.Sequential的工作方式不同? 请考虑以下代码(必须使用“unsafe”编译的控制台应用程序): using System; using System.Runtime.InteropServices; namespace ConsoleApplication3 { static class Program { static void Main() { Inner test = new Inner(); unsafe { Console.WriteLine(“Address of struct = ” + ((int)&test).ToString(“X”)); Console.WriteLine(“Address of First = ” + ((int)&test.First).ToString(“X”)); Console.WriteLine(“Address of NotFirst = ” + ((int)&test.NotFirst).ToString(“X”)); } } } [StructLayout(LayoutKind.Sequential)] public struct Inner { public byte […]