繁体   English   中英

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

[英]What is the best way to move the content of an enumerable objects to an array of objects? See code below

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

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

     //What the next step here?...

     return objects;
}

enumerableByteCodes中的那些字节代表对象吗? 如果不是,为什么不返回byte []?

如果要返回一个byteArray,则可以仅使用LINQ扩展方法

IEnumerable<t>.ToArray() ;

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

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

您也可以使用

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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