1

我有以下课程:

    public class Red
    {
        public List<Blue> theList = new List<Blue>();
    }
    public class Blue
    {
        private Red origin;

        public Blue(ref Red)
        {
            origin = Red;
        }

        public void SomeMethod()
        {
            origin.theList.Add(new Blue(ref origin));//When calling this, i get the error
        }
    }

现在它告诉我,我不能将 origin 作为 ref 传递(无论出于何种原因),但我需要每个 Blue 实例都有一个 Red 的 ref。这样我就可以拥有它的实时版本,并且每个 Blue 实例都将访问 Red 的当前版本(不是副本)

所以我需要以下工作:

    using System;
    public static class Program
    {
        public static Main(string[] Args)
        {
            Red red = new Red();
            red.Add(new Blue(ref red));
            red.Add(new Blue(ref red));
            red.[0].SomeMethod();
            Console.WriteLine(red[0].origin.Count()); //Should be 2, because red was edited after the first blue instance was created
            Console.ReadKey(true);
        }
    }
4

2 回答 2

3

您不需要通过引用传递,因为您不需要修改red' 位置。

public class Red
{
    public List<Blue> theList = new List<Blue>();
}

public class Blue
{
    private Red origin;

    public Blue(Red red)
    {
        origin = red;
    }

    public void SomeMethod()
    {
        origin.theList.Add(new Blue(origin));
    }
}

由于RedBlue引用类型,它们的位置被传递而不是它们的值。

于 2013-06-24T18:42:00.650 回答
0

您不需要ref实例。它是同一个对象的引用。您需要 ref 和 out 来处理整数、字符串等内容。在没有 ref 的情况下按原样传递所有内容。

于 2013-06-24T19:55:46.117 回答