簡體   English   中英

通用TypeCode類型檢查?

[英]Generic TypeCode Type Checking?

我應該避免使用泛型進行類型檢查嗎? 不使用傳統的類型檢查比較( myvar is int ),而是使用類型的類型代碼。

使用泛型,通過類型檢查,您可以創建一個沒有支持常規重載方法任務的參數的方法。 這是無參數方法的問題,它們不能重載。

// "Buffer" is the byte[] while "Peek" is the read/write position. Then Align" is the alignment size in bytes of the buffer.
public type Read<type>() {
    switch( Type.GetTypeCode( typeof( type ) ) ) {
        case System.TypeCode.Boolean:
            bool bool_val = ( Buff[ Peek ] > 0 );
            Peek = ( ++Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)bool_val;
        case System.TypeCode.Byte:
            byte byte_val = Buff[ Peek ];
            Peek = ( ++Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)byte_val;
        case TypeCode.Ushort:
            ushort ushort_val = (ushort)( Buff[ Peek ] | ( Buff[ Peek + 1 ] << 8 ) );
            Peek += 2;
            Peek = ( Peek + ( Align - 1 ) ) & ~( Align - 1 );
            return (type)(object)ushort_val;
        break;
        ...
    }
}

這似乎是使用無參數方法實現重載形式的唯一方法。 這被認為是不好的做法嗎?

您可以使用以下內容使代碼具有通用性:

var size = Marshal.SizeOf(typeof(T));
var subBuffer = new byte[size];
Array.Copy(Buff, Peek, subBuffer, 0, size);
var handle = GCHandle.Alloc(subBuffer, GCHandleType.Pinned);
var ptr = handle.ToIntPtr();
var val = (T)Marshal.PtrToStructure(ptr, typeof(T));
ptr.Free();
Peek += size;
Peek = ( Peek + ( Align - 1 ) ) & ~( Align - 1 );
return val;

但是,如果這對您的用例存在性能問題,那么提供硬編碼的專用版本可能並不是一種糟糕的方法,因為沒有任何明顯的替代方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM