将可枚举对象的内容移动到对象数组的最佳方法是什么?见下面的代码

时间:2010-12-16 10:10:37

标签: c#

public object[] GetByteCodes(IEnumerable<byte> enumerableByteCodes)
{

     object[] objects = new object[enumerableByteCodes.Count()];

     //What the next step here?...

     return objects;
}

2 个答案:

答案 0 :(得分:3)

enumerableByteCodes中的那些字节是否代表对象?如果没有,为什么不返回一个字节[]?

如果要返回byteArray,可以使用

上的LINQ扩展方法

IEnumerable<t>.ToArray();

如果要将其作为对象返回,可以使用Select LINQ扩展来执行此操作。

enumerableByteCodes.Select(t=> (object)t).ToArray();

您也可以使用

enumerableBytes.OfType<object>().ToArray();

答案 1 :(得分:2)

byteCodes = enumerableByteCodes.ToArray();

我只想制作这个功能:

public byte[] GetByteCode(IEnumerable<byte> enumerableByteCodes)
{
    return enumerableByteCodes.ToArray();
}

为什么使用object[],因为您的通用类型是byte

更新

由于您必须拥有object[],因此您需要投射每个成员:

public object[] GetByteCode(IEnumerable<byte> enumerableByteCodes)
{
    return enumerableByteCodes.Select(x => (object)x).ToArray();
}