请看一下代码。浏览一下不应该花费太长时间。
class Teacher
{
private int _id;
public int ID
{
get { return _id; }
set { _id = value; }
}
private string _message;
public string Message
{
get { return _message; }
set { _message = value; }
}
public Teacher(int id, string msg)
{
_id = id;
_message = msg;
}
private List<Course> _items;
public List<Course> GetCourses()
{
return _items;
}
public Teacher()
{
if (_items == null)
{
_items = new List<Course>();
}
_items.Add(new Course(1, "cpp"));
_items.Add(new Course(1, "java"));
_items.Add(new Course(1, "cs"));
}
public void Show()
{
Console.WriteLine(this._id);
Console.WriteLine(this._message);
}
public void ShowList()
{
foreach(Course c in _items)
{
c.Show();
}
}
}
class Course
{
private int _id;
public int ID
{
get { return _id; }
set { _id = value; }
}
private string _message;
public string Message
{
get { return _message; }
set { _message = value; }
}
public Course(int id, string msg)
{
_id = id;
_message = msg;
}
private List<Teacher> _items;
public List<Teacher> GetTeachers()
{
return _items;
}
public Course()
{
if(_items == null)
{
_items = new List<Teacher>();
}
_items.Add(new Teacher(1, "ttt"));
_items.Add(new Teacher(1, "ppp"));
_items.Add(new Teacher(1, "mmm"));
}
public void Show()
{
Console.WriteLine(this._id);
Console.WriteLine(this._message);
}
public void ShowList()
{
foreach (Teacher t in _items)
{
t.Show();
}
}
}
class Program
{
static void Main(string[] args)
{
Teacher t = new Teacher();
t.ID = 1;
t.Message = "Damn";
t.Show();
t.ShowList();
t.GetCourses().Clear();
t.Show();
t.ShowList();
Console.ReadLine();
}
}
GetCourses()
返回了_items的一个引用,所以调用t.GetCourses().Clear();
会清除Teacher
实例中的底层Course
列表。
我希望防止这种行为。也就是说,GetCourses()
将返回一个列表,但它不可修改。
如何实现?
List<T>
中没有什么可以创建深度克隆的东西。根据我的经验,克隆通常是不鼓励的。 - Jon Skeet