.net - Converting `Int32` to `T` and `T []` to `Int32 []` in C# -
i attempting write simple function use randomnumbergenerator class return array of int16
, int32
or int64
based on generic argument.
however, no matter how try structure code, cannot seem past illegal conversion t []
short/int/long []
, nor conversion intxx
t
. please see 2 comments in code below.
it seems missing basic construct allow way around this. thoughts?
public static void generaterandom<t> (t [] data, bool nonzeroonly = false) t: struct, system.icomparable, system.iformattable, system.iconvertible { int size = 0; byte [] bytes = null; if ((typeof(t) != typeof(byte)) && (typeof(t) != typeof(short)) && (typeof(t) != typeof(int)) && (typeof(t) != typeof(long))) { throw (new system.argumentexception("this method accepts types [byte], [int16], [int32], or [int64].", "<t>")); } if (typeof(t) == typeof(byte)) { using (system.security.cryptography.randomnumbergenerator generator = system.security.cryptography.randomnumbergenerator.create()) { // invalid cast (implicit or explicit) t [] byte []. if (nonzeroonly) { generator.getnonzerobytes(data); } else { generator.getbytes(data); } } } else { size = system.runtime.interopservices.marshal.sizeof(typeof(t)); bytes = new byte [data.length * size]; using (system.security.cryptography.randomnumbergenerator generator = system.security.cryptography.randomnumbergenerator.create()) { if (nonzeroonly) { generator.getnonzerobytes((byte []) system.convert.changetype(data, typeof(byte []))); } else { generator.getbytes((byte []) system.convert.changetype(data, typeof(byte []))); } } using (system.io.memorystream stream = new system.io.memorystream(bytes)) { using (system.io.binaryreader reader = new system.io.binaryreader(stream)) { // invalid cast (implicit or explicit) short/int/long t. if (typeof(t) == typeof(short)) { (int i=0; i<bytes.length; i+=size) { data[i] = reader.readint16(); } } else if (typeof(t) == typeof(int)) { (int i=0; i<bytes.length; i+=size) { data[i] = reader.readint32(); } } else if (typeof(t) == typeof(long)) { (int i=0; i<bytes.length; i+=size) { data[i] = reader.readint64(); } } } } } }
on side note, there more efficient way of converting byte []
intxx []
without using stream , binary reader?
you can this, int
t
:
void foo<t>(t[] data) { ... int v = r.next(255); // limit byte.max simplicity data[i] = (t) convert.changetype(v, typeof(t)); }
Comments
Post a Comment