VB.NET特性之FieldOffset特性

VB.NET特性<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

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

 

    則這些元素在內存中的位置,如圖:

   

<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" />

這樣就可以通過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)

輸出如:

 

 

 

這樣就可以解決很多轉換的工作,而且比使用數學運算符更快!

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章