c# - Generic TypeCode Type Checking? -


should avoid type checking generics? not using traditional type checking comparisons(myvar int), rather using type's typecode.

using generics, type checking allows create single method without parameters supports tasks of regular overloaded methods. problem parameter-less methods, cannot overloaded.

// "buffer" byte[] while "peek" read/write position. align" alignment size in bytes of 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;         ...     } } 

this seems way achieve form of overloading parameter-less methods. considered bad practice?

you can make code generic this:

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; 

however, if suffers performance issues use case, providing hard-coded specialized versions isn't bad way it, since there aren't obvious alternatives.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -