【发布时间】:2013-06-24 18:40:28
【问题描述】:
我有以下课程:
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 的引用。这样我就可以拥有它的实时版本,并且每个 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);
}
}
【问题讨论】:
-
您的术语不正确。你的
origin是一个field(类级变量),而不是一个property。编译器的确切错误消息是什么(编辑还是运行时异常?)?
标签: c# properties instance ref