解剖SQLSERVER 第三篇 ?數據類型的實現(譯)
?
http://improve.dk/implementing-data-types-in-orcamdf/
實現對SQLSERVER數據類型的解析在OrcaMDF 軟件里面是一件比較簡單的事,只需要實現ISqlType 接口
public interface ISqlType { bool IsVariableLength { get ; } short ? FixedLength { get ; } object GetValue( byte [] value); }
IsVariableLength ?返回數據類型是否是定長的還是變長的。
FixedLength ?返回定長數據類型的長度,否則他返回null
數據類型解釋器不關心變長字段的長度,輸入的字節大小會決定長度
最后, GetValue ?將輸入字節參數進行解釋并將字節解釋為相關的.NET對象
?
?
SqlInt實現
int類型作為定長類型是非常簡單的,能直接使用BitConverter進行轉換
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 ); } }
?
相關測試
[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 實現
nvarchar 類型也是非常簡單的,注意,如果是可變長度我們返回長度的結果是null
ISqlType 接口實現必須是無狀態的
GetValue 簡單的將輸入的字節的數進行轉換,這將轉換為相關的.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); } }
?
相關測試
[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)); } }
其他類型的實現
OrcaMDF 軟件現在支持12種數據類型,以后將會支持datetime和bit類型,因為這兩個類型相比起其他類型有些特殊
其余類型我以后也將會進行實現
?
第三篇完
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
