360教程:是一个免费提供流行杀毒软件教程、在线学习分享的学习平台!

VB.NET特征之FieldOffset特征

时间:2022-10-18作者:未知来源:360教程人气:

VB.NET特性

-----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)

输出如:










这样就可以解决很多转换的工作,而且比使用数学运算符更快!



关键词:VB.NET特征之FieldOffset特征




Copyright © 2012-2018 360教程(http://www.360sd.cn) .All Rights Reserved 网站地图 友情链接

免责声明:本站资源均来自互联网收集 如有侵犯到您利益的地方请及时联系管理删除,敬请见谅!

QQ:1006262270   邮箱:kfyvi376850063@126.com   手机版