简体   繁体   中英

Converting `Int32` to `T` and `T []` to `Int32 []` in C#

I was attempting to write a simple function that would use the RandomNumberGenerator class to return an array of Int16 , Int32 or Int64 based on a generic argument.

However, no matter how I try to structure the code, I cannot seem to get past the illegal conversion from T [] to short/int/long [] , nor the conversion from IntXX to T . Please see the two comments in the code below.

It seems I am missing a basic construct that would allow a way around this. Any thoughts?

public static void GenerateRandom<T> (T [] data, bool nonZeroOnly = false)
    where 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 only 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) from T [] to 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) from short/int/long to T.
                if (typeof(T) == typeof(short)) { for (int i=0; i<bytes.Length; i+=size) { data[i] = reader.ReadInt16(); } }
                else if (typeof(T) == typeof(int)) { for (int i=0; i<bytes.Length; i+=size) { data[i] = reader.ReadInt32(); } }
                else if (typeof(T) == typeof(long)) { for (int i=0; i<bytes.Length; i+=size) { data[i] = reader.ReadInt64(); } }
            }
        }
    }
}

On a side note, is there a more efficient way of converting a byte [] to a IntXX [] without using a stream and binary reader?

You can do this, to get from int to T :

void Foo<T>(T[] data)
{
    ...
    int v = r.Next(255);  // limit to byte.max for simplicity
    data[i] = (T) Convert.ChangeType(v, typeof(T));
}

I think you are trying to be clever here and in the process making things far too complex. Just write threee separate methods:

Int16[] GenerateRandomShorts()
Int32[] GenerateRandomInts()
Int64[] GenerateRandomLongs()

There is absolutely no reason to use generics here, and the problems you are facing are the result of swimming against the current.

Simply use non-generic overloads and let the compiler pick the one to use based on the type of the first argument:

public static void GenerateRandom(byte[] data, bool nonZeroOnly = false)
{
    using (var generator = RandomNumberGenerator.Create())
    {
        if (nonZeroOnly) { generator.GetNonZeroBytes(data); }
        else { generator.GetBytes(data); }
    }
}

public static void GenerateRandom(short[] data, bool nonZeroOnly = false)
{
    var size = sizeof(short);
    var bytes = new byte[data.Length * size];

    GenerateRandom(bytes, nonZeroOnly);

    for (var i = 0; i < data.Length; ++i) {
        data[i] = BitConverter.ToInt16(bytes, i * size);
    }
}

Two more overloads like the last one would take care of int and long .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM