簡體   English   中英

怎么把System.Byte []轉換成System.UInt64 []?

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

我嘗試將任何C#對象轉換為System.UInt64 []。

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

例如,將對象f1,f2轉換為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); //---  ?

產量

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

告訴我如何編寫功能代碼Convert<T>(object value) ,其中T輸出類型值ulong嗎?

限制:Framework 2.0,可以從對象f獲取輸入類型。

原來是唯一的方法

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

不幸的是輸入類型不一定是字節[]

使用linq表達式:

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();

這適用於源中的所有數據類型,這些數據類型可以強制轉換為“ System.UInt64”。

編輯:正如Thomas Levesque指出Cast<System.UInt64>()在這里不起作用,因此我們必須在此處使用Select(ConvertFunction)

您可以使用Array.ConvertAll

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

解決了這個問題,但也許有更好的決定

    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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM