解剖SQLSERVER 第三篇 ?數(shù)據(jù)類型的實(shí)現(xiàn)(譯)
?
http://improve.dk/implementing-data-types-in-orcamdf/
實(shí)現(xiàn)對SQLSERVER數(shù)據(jù)類型的解析在OrcaMDF 軟件里面是一件比較簡單的事,只需要實(shí)現(xiàn)ISqlType 接口
public
interface
ISqlType
{
bool
IsVariableLength {
get
; }
short
? FixedLength {
get
; }
object
GetValue(
byte
[] value);
}
IsVariableLength ?返回?cái)?shù)據(jù)類型是否是定長的還是變長的。
FixedLength ?返回定長數(shù)據(jù)類型的長度,否則他返回null
數(shù)據(jù)類型解釋器不關(guān)心變長字段的長度,輸入的字節(jié)大小會(huì)決定長度
最后, GetValue ?將輸入字節(jié)參數(shù)進(jìn)行解釋并將字節(jié)解釋為相關(guān)的.NET對象
?
?
SqlInt實(shí)現(xiàn)
int類型作為定長類型是非常簡單的,能直接使用BitConverter進(jìn)行轉(zhuǎn)換
public
class
SqlInt : ISqlType
{
public
bool
IsVariableLength
{
get
{
return
false
; }
}
public
short
?
FixedLength
{
get
{
return
4
; }
}
public
object
GetValue(
byte
[] value)
{
if
(value.Length !=
4
)
throw
new
ArgumentException(
"
Invalid value length:
"
+
value.Length);
return
BitConverter.ToInt32(value,
0
);
}
}
?
相關(guān)測試
[TestFixture]
public
class
SqlIntTests
{
[Test]
public
void
GetValue()
{
var
type =
new
SqlInt();
byte
[] input;
input
=
new
byte
[] {
0x5e
,
0x3b
,
0x27
,
0x2a
};
Assert.AreEqual(
707214174
, Convert.ToInt32(type.GetValue(input)));
input
=
new
byte
[] {
0x8d
,
0xf9
,
0xaa
,
0x30
};
Assert.AreEqual(
816511373
, Convert.ToInt32(type.GetValue(input)));
input
=
new
byte
[] {
0x7a
,
0x4a
,
0x72
,
0xe2
};
Assert.AreEqual(
-
495826310
, Convert.ToInt32(type.GetValue(input)));
}
[Test]
public
void
Length()
{
var
type =
new
SqlInt();
Assert.Throws
<ArgumentException>(() => type.GetValue(
new
byte
[
3
]));
Assert.Throws
<ArgumentException>(() => type.GetValue(
new
byte
[
5
]));
}
}
?
?
SqlNVarchar 實(shí)現(xiàn)
nvarchar 類型也是非常簡單的,注意,如果是可變長度我們返回長度的結(jié)果是null
ISqlType 接口實(shí)現(xiàn)必須是無狀態(tài)的
GetValue 簡單的將輸入的字節(jié)的數(shù)進(jìn)行轉(zhuǎn)換,這將轉(zhuǎn)換為相關(guān)的.NET 類型,這里是string類型
public
class
SqlNVarchar : ISqlType
{
public
bool
IsVariableLength
{
get
{
return
true
; }
}
public
short
?
FixedLength
{
get
{
return
null
; }
}
public
object
GetValue(
byte
[] value)
{
return
Encoding.Unicode.GetString(value);
}
}
?
相關(guān)測試
[TestFixture]
public
class
SqlNvarcharTests
{
[Test]
public
void
GetValue()
{
var
type =
new
SqlNVarchar();
byte
[] input =
new
byte
[] {
0x47
,
0x04
,
0x2f
,
0x04
,
0xe6
,
0x00
};
Assert.AreEqual(
"
u0447u042fu00e6
"
, (
string
)type.GetValue(input));
}
}
其他類型的實(shí)現(xiàn)
OrcaMDF 軟件現(xiàn)在支持12種數(shù)據(jù)類型,以后將會(huì)支持datetime和bit類型,因?yàn)檫@兩個(gè)類型相比起其他類型有些特殊
其余類型我以后也將會(huì)進(jìn)行實(shí)現(xiàn)
?
第三篇完
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

