开发者

How to extract elements of an array in object type in c#?

开发者 https://www.devze.com 2023-03-28 19:47 出处:网络
I have an object which contains an array of any type 开发者_JAVA技巧(not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I e

I have an object which contains an array of any type 开发者_JAVA技巧(not a priory known type. So I cannot a simple cast in the code because I can determine the type just in the run-time!). How can I extract the content of array? For example:

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?`


An array is an IEnumerable<T>, using Covariance an IEnumerable<object>. That means any array is an 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());
}


You can cast it.

var myTempArray = obj as IEnumerable;

foreach (object item in myTempArray)
   ...


EDIT (Again)

If you know that the object is an array and you don't know the type of the array you can just cast it as an object[]. This will defiantly work if all you have to do is call toString().

For example

(obj as object[])


You need to cast it back to int[] and then extract the elements. After all, the fact that you know that is an array of integer doesn't reflect the fact that you're stating that is an object.

Look at it from the point of view of the compiler. All he know is that you've defined an object variable that, at that point, happens to be an array of integer, but which could change later on to another thing.. after all is just an object.

The constraints checks are performed by the runtime when you do the cast, so, logically, the compiler won't let you just use it as an array but require you to first CAST it to an array.


In .net 4.0 you could do make unnesscessary use of the dynamic keyword,

dynamic object obj = array;
Console.Write(obj[0].ToString());


Once you assign the array as the value of obj, you have made a cast. You will have to retrieve an item by casting again:

int[] array = new int[] { 0, 1, 2 };
object obj = array;

var i = ((int[])obj)[0];

If you don't know the type of the array, you will have to use generics:

object obj;

void StoreArray<T>(T array)
{
    obj = array;
}

T GetValue<T>(int index)
{
    return (T)(obj as T[])[index];
}

Note: unntested sample.

0

精彩评论

暂无评论...
验证码 换一张
取 消