简体   繁体   中英

get a reference of object from List of objects in c#

i want to get a reference from a list of objects on an object ,

so the reference i want object type

i will explain in the following example

i have a method like

method (ref Foo foo)
{
//
}

and i have a list of Foo

List<Foo> listFoo;

and i want to call this

method(ref listFoo[i])

so this return a reference of a listfoo and i want the reference of the foo number i in the list

thanks

If you mean the direct array reference; you cannot obtain that via a list. Not least, this is because the list is free to reassign the underlying array at any point - rendering your reference confusing at best.

If it was an array, the you could use the method(ref arr[index]) approach you mention; but only with arrays.

Note: this trick is only useful in two scenarios:

  • you want to reassign the value in the array
  • you want to access a struct in-situ, without causing it to be copied

For most purposes, passing the object reference is fine, ie

Method(Foo foo); // Foo is a class
...
Method(list[i]); // pass the reference to the object, unrelated to the container

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