简体   繁体   中英

How convert System.Byte[] To System.UInt64[]?

I try converting any C# object to System.UInt64[].

System.Byte[] to System.UInt64[].
double[] to System.UInt64[].
int[] to System.UInt64[].

Example, convert object f1, f2 to ulong b[]

 object f1 = new Byte[3] { 1, 2, 3 };  
 ulong b[]  = Convert<ulong>(f1); //---  ?

 object f2 = new double[3] { 1, 2, 3 };  
 b  = Convert<ulong>(f2); //---  ?

Output

b[0] = 1
b[1] = 2
b[3] = 3

tell me how to write the function code Convert<T>(object value) , where T output type value ulong ?

restrictions: Framework 2.0, input type can be obtained from the object f.

It turned out the only way to make

 ulong[] b = Array.ConvertAll((byte[])f, element => Convert.ToUInt64(element));

Unfortunately input type is not necessarily be byte []

Use a linq expression:

System.Byte[] source = new System.Byte[] { 1, 2, 3 };
// does not work: System.UInt64[] target = source.Cast<System.UInt64>().ToArray();
System.UInt64[] target = source.Select(b => (System.UInt64)b).ToArray();

This works for all datatypes in source which can be casted to 'System.UInt64'.

Edit: As Thomas Levesque pointed out Cast<System.UInt64>() does not work here, so we must use a Select(ConvertFunction) here.

You can use Array.ConvertAll :

byte[] bytes = new byte[3] { 1, 2, 3 };
ulong[] ulongs = Array.ConvertAll<byte, ulong>(b => (ulong)b);

Solved the problem with this, but maybe there are better decisions

    static T[] MyConvert<T>(object value){
        T[] ret = null;
        if (value is Array)
        {
            Array arr = value as Array;
            ret = new T[arr.Length];
            for (int i = 0 ; i < arr.Length; i++ )
            {
                ret[i] =  (T)Convert.ChangeType(arr.GetValue(i), typeof(T));.
            }
        }
        return ret;
    }

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