gpt4 book ai didi

c# - 可以在列表中存储对对象的引用吗?

转载 作者:太空狗 更新时间:2023-10-29 22:10:57 27 4
gpt4 key购买 nike

我希望能够为列表对象赋值而不直接引用它们:

伪例子:

List<int> intList = new List<int> { 0 };
???? intPointer = ref intlist[0];

*intPointer = 1; // I know * isn't possible here, but it is what I'd like to do

Console.WriteLine(intList[0]);

它会输出1

我认为这是不可能的,但我只是想确保我没有遗漏任何东西。

此外,我不是在寻找使用 unsafe 的示例,我很好奇这在托管代码中是否可行。

最佳答案

C# 没有“ref locals”的概念 (the CLR does though)。因此,您需要将这些值包装在可以改变的引用类型中。例如,

public class Ref<T> where T : struct
{
public T Value {get; set;}
}

List<Ref<int>> intRefList = new List<Ref<int>>();
var myIntRef = new Ref<int> { Value = 1 };
intRefList.Add(myIntRef);

Console.WriteLine(myIntRef.Value);//1

Console.WriteLine(intRefList[0].Value);//1

myIntRef.Value = 2;

Console.WriteLine(intRefList[0].Value);//2

编辑:添加了 C# 7.0 ref locals但它们仍然不能以这种方式使用,因为您不能将 ref locals 放入数组或列表中。

关于c# - 可以在列表中存储对对象的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13371433/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com