VB.NET特性
-----FieldOffset特性
在选择显示布局的时候,结构中的所有变量的定义必须包含 FieldOffset特性。这个特性指定了距结构开始处的距离(以字节位单位)。
Imports System.Runtime.InteropServices
1<structlayout(layoutkind.explicit)> _
2
3Structure test
4
5<fieldoffset(0)> Dim Red as Byte
6
7<fieldoffset(1)> Dim Green as Byte
8
9<fieldoffset(2)> Dim Blue as Byte
10
11<fieldoffset(3)> Dim Alpha as Byte
12
13End Structure
14
15StructLayout特性与FieldOffset特性可以实现 **联合** (union)。 **联合** (union)已经被多种语言(如 c和c++)采用,但是vb却不具备这一语言特性。 **联合** (union)是一种可以使得结构中的两个或多个元素在内存中重叠,以及使用不同的名称来指示同一内存位置。
16
17在.NET中, **联合** (union)的关键在于支持显示结构布局。
18
19如:
20
21Imports System.Runtime.InteropServices
22
23<structlayout(layoutkind.explicit)> _
24
25Structure test
26
27<fieldoffset(0)> Dim Red as Byte
28
29<fieldoffset(1)> Dim Green as Byte
30
31<fieldoffset(2)> Dim Blue as Byte
32
33<fieldoffset(3)> Dim Alpha as Byte
34
35<fieldoffset(0)> Dim Value as Integer
36
37End Structure
38
39则这些元素在内存中的位置,如图:
40
41
42
43这样就可以通过 Value 字段将4个字节作为一个整体进行访问。
44
45'拆分
46
47Dim rgb as test
48
49rgb.Value=&H112233 '1122867
50
51Console.Write("Red={0},Green={1},Blue={2}",rgb.Red,rgb.Green,rgb.Blue)
52
53输出如:
54
55
56
57‘ 合并
58
59rgb.Red=51
60
61rgb.Green=34
62
63rgb.Blue=17
64
65Console.Write(rgb.Value)
66
67输出如:
68
69
70
71这样就可以解决很多转换的工作,而且比使用数学运算符更快!</fieldoffset(0)></fieldoffset(3)></fieldoffset(2)></fieldoffset(1)></fieldoffset(0)></structlayout(layoutkind.explicit)></fieldoffset(3)></fieldoffset(2)></fieldoffset(1)></fieldoffset(0)></structlayout(layoutkind.explicit)>