简体   繁体   English

C#如何访问对象内的数组信息未知类型

[英]C# how to access array info unknown type within object

I have an object called SampleObject that holds an array of strings called StringArray. 我有一个名为SampleObject的对象,其中包含一个名为StringArray的字符串数组。 In order for me to access the first element in that array I need to write: 为了使我能够访问该数组中的第一个元素,我需要编写:

((string[])(SampleObject))[0]

However if I were to not know the type of the array how would I be able to approach this? 但是,如果我不知道数组的类型,我将如何处理呢?

((SampleObject.GetType())(SampleObject))[0];

I tried something like this but it expects a method name. 我尝试了类似的方法,但是它需要一个方法名称。

Thanks. 谢谢。

You can use Array.GetValue - all array types are derived from Array , whatever the element type is. 您可以使用Array.GetValue所有数组类型都派生自Array ,无论元素类型是什么。 You may need to think carefully about rectangular arrays though, and arrays with a non-zero lower bound. 但是,您可能需要仔细考虑矩形数组和下限为非零的数组。

While Jon's answer is correct, you can abuse array co-variance, provided you have a normal (one dimensional, starting at 0) array of reference type. 尽管乔恩的答案是正确的,但前提是您拥有参考类型的普通(一维,从0开始)数组,但您可以滥用数组协方差。

return ((object[])SampleObject)[3];

Return the 3rd element in the array. 返回数组中的第三个元素。 You can also cast it to a non-generic IList if it not only will change the element type, but possibly the container itself. 如果它不仅会更改元素类型,而且可能会更改容器本身,也可以将其IList转换为非通用IList

If they are going to be based on c# object class, you can use GetType() - this will return a System.Type (see http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx ). 如果它们将基于c#对象类,则可以使用GetType()-这将返回System.Type(请参阅http://msdn.microsoft.com/zh-cn/library/system.object.gettype。 aspx )。 Otherwise you could base them off your own base object that has a type define for all possible values. 否则,您可以将它们基于自己的基础对象,该基础对象具有为所有可能值定义的类型。

Another approach would be to use Reflection to determine the type and to manipulate the data. 另一种方法是使用反射来确定类型并操纵数据。 While this is applicable on all types of objects (not only arrays), for the scenario you described I would go with the solution of Jon Skeet. 尽管这适用于所有类型的对象(不仅是数组),但对于您描述的场景,我将采用Jon Skeet的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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