抽象数组长度? [英] Abstract Array Length?

查看:88
本文介绍了抽象数组长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 object 类型的变量,我知道它包含一个数组。我对所包含的类型一无所知(它可以变化),我也不需要。我想要的只是获取数组大小/长度(该数组中元素的数量)。



在C#中执行此操作的正确方法是什么?

解决方案

您可以将对象转换为数组

  object  o =  new   int  [ 3  ]。 
string test =(o as Array).Length.ToString();
MessageBox.Show(test);





或者如果是列表:

< pre lang =c#> object o = new List< int>( 3 );
string test =(o as IList).Count.ToString();
MessageBox.Show(test)



你可以使用运算符结合两者

 如果(o   IList)size =( o  as  IList).Count; 
如果(o 数组)size =(o as 数组).Length;





更新:

经过测试, int [] 也是 IList ,但是 List< int> 不是数组,你可以在所有情况下使用 IList


你好,



你可以试试这个:

  int  lengthOfArray =((Array)obj).Length;  //  将obj更改为对象名称 



希望这有帮助。


在不知道对象是Array类型的情况下无法获得长度。您可以使用''is''运算符检查对象实例是否为数组类型,并使用''as''运算符对其进行转换。



/Edit.

尝试使用ICollection强制转换Object并使用Count属性。


I have a variable of type object, which I know to contain an array. I know nothing about the contained type (it can vary), and neither I need to. All I want is to get the array size/length (number of elements in that array).

What is the right way of doing it in C#?

解决方案

You can cast your object to Array

object o = new int[3];
string test = (o as Array).Length.ToString();
MessageBox.Show(test);



or if it is a list:

object o = new List<int>(3);
string test = (o as IList).Count.ToString();
MessageBox.Show(test)


and you can combine both using the operator is

if(o is IList) size = (o as IList).Count;
if(o is Array) size = (o as Array).Length;



Update:
After test, int[] is IList too, but the List<int> is not Array, you may use the IList in all case


Hi,

You can try this:

int lengthOfArray = ((Array)obj).Length; // change obj into the name of your object


Hope this helps.


its impossible to get the length without know the object is of type Array. You can check whether the object instance is of type array using ''is'' operator and conver it using ''as'' operator.

/Edit.
try casting the Object with ICollection and use the Count Property.


这篇关于抽象数组长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆