VB.NET特性之FieldOffset特性
点击次数:56 次 发布日期:2008-11-06 08:06:06 作者:源代码网
|
-----FieldOffset特性 在选择显示布局的时候,结构中的所有变量的定义必须包含FieldOffset特性。这个特性指定了距结构开始处的距离(以字节位单位)。 Imports System.Runtime.InteropServices <StructLayout(LayoutKind.Explicit)> _ Structure test <FieldOffset(0)>Dim Red as Byte <FieldOffset(1)>Dim Green as Byte <FieldOffset(2)>Dim Blue as Byte <FieldOffset(3)>Dim Alpha as Byte End Structure StructLayout特性与FieldOffset特性可以实现联合(union)。联合(union)已经被多种语言(如 c和c )采用,但是vb却不具备这一语言特性。联合(union)是一种可以使得结构中的两个或多个元素在内存中重叠,以及使用不同的名称来指示同一内存位置。 在.NET中,联合(union)的关键在于支持显示结构布局。 如: Imports System.Runtime.InteropServices <StructLayout(LayoutKind.Explicit)> _ Structure test <FieldOffset(0)>Dim Red as Byte <FieldOffset(1)>Dim Green as Byte <FieldOffset(2)>Dim Blue as Byte <FieldOffset(3)>Dim Alpha as Byte <FieldOffset(0)>Dim Value as Integer End Structure 则这些元素在内存中的位置,如图: 这样就可以通过Value 字段将4个字节作为一个整体进行访问。 "拆分 Dim rgb as test rgb.Value=&H112233 "1122867 Console.Write("Red={0},Green={1},Blue={2}",rgb.Red,rgb.Green,rgb.Blue) 输出如: ‘合并 rgb.Red=51 rgb.Green=34 rgb.Blue=17 Console.Write(rgb.Value) 输出如: 这样就可以解决很多转换的工作,而且比使用数学运算符更快! 源代码网推荐 源代码网供稿. |
