泛型类型代码类型检查

本文关键字:检查 类型 代码 泛型类型 | 更新日期: 2023-09-27 17:56:04

我应该避免使用泛型进行类型检查吗?不使用传统的类型检查比较(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;

但是,如果这在您的用例中存在性能问题,那么提供硬编码的专用版本可能不是一个坏方法,因为没有任何明显的替代方案。