gpt4 book ai didi

c# - 在不知道显式类型的情况下将装箱的可枚举对象转换为对象数组

转载 作者:行者123 更新时间:2023-12-02 17:51:22 25 4
gpt4 key购买 nike

我有一些代码可以从表达式树中提取一个装箱的可枚举实例。代码需要将其转换为object[]。

到目前为止,我还没有假设它会是 IEnumerable<string>因此将其转换为 .ToArray() .

情况已经改变,现在它也可能是 IEnumerable<int> 。我还需要把盒子改成object[]并且并不真正关心类型是什么。

<小时/>
object list = Expression.Lambda(methodCallExpression.Object).Compile().DynamicInvoke();

var enumerable = (IEnumerable<string>)list;
object[] values = enumerable.ToArray();
<小时/>

更新:

字符串是引用,整数是值类型。我发现虽然我可以装箱对整数数组的引用,但我不能假装它是装箱整数的数组,因为整数不能装箱。

An exception of type 'System.InvalidCastException' occurred in System.Core.dll but was not handled in user code Additional information: Unable to cast object of type 'System.Collections.Generic.List1[System.Int32]' to type
'System.Collections.Generic.IEnumerable
1[System.Object]'.

object list = Expression.Lambda(methodCallExpression.Object).Compile().DynamicInvoke(); 
var enumerable = (IEnumerable<object>)list;
object[] values = enumerable.ToArray();

最佳答案

只需在 ToArray 之前调用 Cast:

object[] values = enumerable.Cast<object>().ToArray();

请注意,这会转换每个项目,而不是整个集合。您无法将ints集合“转换”为对象集合,您必须将每个项目转换为对象(即框他们)。

关于c# - 在不知道显式类型的情况下将装箱的可枚举对象转换为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com