简体   繁体   中英

C#: How to access array methods from parent object?

My ctor return an object which is multidimentional array. Depends on constructor argument, the object returned by ctor can be different rank array, but always int.

object arr = new int[2,2,2];

or

object arr = new int[2,2,2,2,2];

or

object arr = new int[0,0];

Having arr object constructed, and knowing what it is ( GetType() ), I'd like to access array methods like Rank , GetLength , GetValue etc. How I can access child specific methods from the object level? For now I have only four methods for arr object accessible: Equals , GetHashCode , GetType , and ToString

Cast the object into an array, like this:

((int[])arr).Rank
((int[])arr).GetLength()

or

(arr as int[]).Rank

You could just declare your variable as Array :

Array arr = new int[2,2,2,2,2];
int rank = arr.Rank;

Or cast to Array:

object arr = new int[2,2,2,2,2];
Array array = (Array)arr;

您必须将其强制转换回Array对象,然后这些方法将可用!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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