开发者

How to retrieve Object from arraylist in c#

开发者 https://www.devze.com 2023-01-04 19:46 出处:网络
How to retrieve Object and its member from arraylist开发者_运维知识库 in c#.You mean like this?

How to retrieve Object and its member from arraylist开发者_运维知识库 in c#.


You mean like this?

ArrayList list = new ArrayList();
YourObject myObject = new YourObject();

list.Add(myObject);    

YourObject obj = (YourObject)list[0];

To loop through:

foreach(object o in list)
{
   YourObject myObject = (YourObject)o;  
  .......
}

Information on ArrayList


    object[] anArray = arrayListObject.ToArray();
    for(int i = 0; i < anArray.Length; i++)
       Console.WriteLine(((MyType)anArray[i]).PropertyName); // cast type MyType onto object instance, then retrieve attribute


Here's an example of a simple ArrayList being populated with a new KeyValuePair object. I then pull the object back out of the ArrayList, cast it back to its original type and access it property.

var testObject = new KeyValuePair<string, string>("test", "property");
var list = new ArrayList();
list.Add(testObject);
var fetch = (KeyValuePair<string, string>)list[0];
var endValue = fetch.Value;


You should use generic collections for this. Use the generic ArrayList so you dont have to cast the object when you are trying to get it out of the array.


You can also use extension methods:

ArrayList list = new ArrayList();
// If all objects in the list are of the same type
IEnumerable<MyObject> myenumerator = list.Cast<MyObject>();
// Only get objects of a certain type, ignoring others
IEnumerable<MyObject> myenumerator = list.OfType<MyObject>();

Or if you're not using a newer version of .Net, check the object type and cast using is/as

list[0] is MyObject; // returns true if it's an MyObject
list[0] as MyObject; // returns the MyObject if it's a MyObject, or null if it's something else

Edit: But if you're using a newer version of .Net...

I strongly suggest you use the Generic collections in System.Collections.Generic

var list = new List<MyObject>(); // The list is constructed to work on types of MyObject
MyObject obj = list[0];
list.Add(new AnotherObject()); // Compilation fail; AnotherObject is not MyObject


Do a type casting like this:

yourObject = new object[]{"something",123,1.2};

((System.Collections.ArrayList)yourObject)[0];
0

精彩评论

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