C# 保存对列表中特定对象的可读/写引用

C# 保存对列表中特定对象的可读/写引用,c#,foreach,monogame,ref,picking,C#,Foreach,Monogame,Ref,Picking,我在编码方面遇到了障碍。我正在用C#编写代码,用单游戏制作程序 我有一个单位清单,我正试着用它们来做鼠标拾取。我从鼠标中射出一条光线到屏幕上,然后找到它最先击中的对象 // A method to find which units are currently under the mouse. static public void FindPickedUnits(string ID) { foreach (Unit unit in ListDictionary[

我在编码方面遇到了障碍。我正在用C#编写代码,用单游戏制作程序

我有一个单位清单,我正试着用它们来做鼠标拾取。我从鼠标中射出一条光线到屏幕上,然后找到它最先击中的对象

//  A method to find which units are currently under the mouse.
    static public void FindPickedUnits(string ID)
    {

        foreach (Unit unit in ListDictionary[ID])
        {

            //  Run the code to check whether or not it is picked, and returns a float representing how close it is.
            unit.IsPicked = Cursor.Pick(unit.Collisions);

            //  And if it is picked...
            if (unit.IsPicked != null)
            {

                //  We will clone it as the closest unit if none exist, or...
                if (ClosestUnit == null)
                {

                    ClosestUnit = unit;

                }

                //  if one already does, overwrite it if it's even closer.
                else if (unit.IsPicked < ClosestUnit.IsPicked)
                {

                    ClosestUnit = unit;
                    Console.WriteLine("The new closest unit is at X" + unit.Position.X + " Y" + unit.Position.Y);

                }
            }
        }
    }

    //  elsewhere...

    Console.WriteLine("The selected unit's color is " + ClosestUnit.Tint);
//一种查找鼠标当前所在单位的方法。
静态公共void FindPickedUnits(字符串ID)
{
foreach(ListDictionary中的单位[ID])
{
//运行代码以检查是否拾取了它,并返回一个表示其接近程度的浮点值。
unit.IsPicked=光标.Pick(unit.Collisions);
//如果它被选中。。。
如果(unit.IsPicked!=null)
{
//如果不存在,我们将把它克隆为最近的单位,或者。。。
if(ClosestUnit==null)
{
闭合时间=单位;
}
//如果已经有,如果更接近,则覆盖它。
否则如果(unit.IsPicked
这段代码将拾取的单元克隆到ClosestUnit对象中,然后我可以随时读取它,没有问题

然而

我不想纯粹读取最近单位的值,我想对它们进行写入,并更改其中的一些。但是如果我更改ClosestUnit对象的值,它不会反映回单位列表中的实际单位

TL;DR I希望能够从单元列表中选择一个单元,然后在代码中的其他地方写入它。如果ClosestUnit对象的功能类似于ref参数,直接引用列表中的实际单元而不是克隆,这将很容易,但我不知道如何让它做到这一点


处理或避免此问题的最有效方法是什么?

具有讽刺意味的是,我的代码始终没有任何问题。我没有意识到ClosestUnit对象本质上是一个类(引用类型),直接引用ListDictionary中的单元,而不是它的克隆


我只需更改ClosestUnit对象上的值,它就会反射回原始值。耶

Unit
是一个类还是一个结构?默认情况下,我习惯将它设置为一个类。。。但我可能会把它改成struct,tbh。为什么?因为我能看到你们有这个问题的一个方法是,若单元是一个结构。类是通过引用传递的,如果您有权访问对象的引用,则可以更改其属性。另一种可能是ListDictionary在返回之前克隆了
Unit
的实例。另外,您的代码实际上并没有“克隆”Unit对象,只是将其分配给
ClosestUnit
…我的错。我只是自然而然地认为对它所做的更改不会反映回原来的单元。我甚至都没试过。但事实上,他们是这样做的。太酷了!我从未想过引用类型的性质意味着什么。我想我学到了一些新东西!