我有以下课程:
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);
}
}