微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 通用TypeCode类型检查?

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐