我应该避免使用泛型进行类型检查吗?不使用传统的类型检查比较(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 …Run Code Online (Sandbox Code Playgroud)