簡體   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