我有一个对象,其中包含任何类型的数组(不是已知的类型.所以我不能在代码中进行简单的转换,因为我可以在运行时确定类型!).如何提取数组的内容?例如:
int[] array = new int[] { 0, 1, 2 };
object obj=array;
...
//Here I know that obj is an array (<b>of a priory unknown type and I cannot use type conversion in the code </b>
//How can extract elements of obj and use them, e.g. write them on the screen?`
Run Code Online (Sandbox Code Playgroud)
Bas*_*Bas 10
数组是IEnumerable<T>,使用协方差a IEnumerable<object>.这意味着任何阵列都是IEnumerable<object>.
int[] array = new int[] { 0, 1, 2 };
object obj=array;
IEnumerable<object> collection = (IEnumerable<object>)obj;
foreach (object item in collection)
{
Console.WriteLine(item.ToString());
}
Run Code Online (Sandbox Code Playgroud)