![](/img/trans.png)
[英]Unable to cast object of type 'System.Byte' to type '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.