c# – 通用TypeCode类型检查?
发布时间:2020-12-15 22:15:42 所属栏目:百科 来源:网络整理
导读:我应该避免使用泛型进行类型检查吗?不使用传统的类型检查比较(myvar是int),而是使用类型的类型代码. 使用泛型,通过类型检查,您可以创建一个没有支持常规重载方法任务的参数的方法.这是无参数方法的问题,它们不能重载. // "Buffer" is the byte[] while "Pee
我应该避免使用泛型进行类型检查吗?不使用传统的类型检查比较(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; 但是,如果这对您的用例存在性能问题,那么提供硬编码的专用版本可能并不是一种糟糕的方法,因为没有任何明显的替代方案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |