简体   繁体   English

从C#中的对象列表中获取对象的引用

[英]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 所以这返回一个listfoo的引用,而我想要列表中的foo数字的引用

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; 如果是数组,则可以使用您提到的method(ref arr[index])方法; 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 您想要就地访问struct ,而不会导致其被复制

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

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

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