设置未调用List对象的属性

时间:2016-08-24 14:17:08

标签: c#

有人可以帮助我吗? 似乎没有调用Set。我怎么能绕过这个?

请注意,_students被设置为属性网格的selectedObject。因此,在UI中完成添加。

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Record
{
    List<Student> _students = new List<Students>();

    public List<Student> Students 
    {
        get
        {
            return _students;
        }
        set
        {
            // track changes here...
            MessageBox.Show("value set!"); // this doesn't get called

            _students = value;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

现在,你只需设置_students。

如果您希望执行此setter,则必须转到Students = new List<Student<();而不是_students = new List<Student>();

答案 1 :(得分:1)

我认为你对set对列表的处理方式存在问题。只有在您设置列表时,才会看到有关将学生添加到Record.Students的消息。

void Main()
{
    Student s = new Student() {
      Name = "fred",
      Age = 10
      };
    List<Student> _s = new List<Student>();
    _s.Add(s);

    Record r = new Record();
    r.Students = _s;  //You'll get a message here
    r.Students.Add(s);  //No message here
}

// Define other methods and classes here
public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Record
{
    List<Student> _students = new List<Student>();

    public List<Student> Students 
    {
        get
        {
            return _students;
        }
        set
        {
            // track changes here...
            MessageBox.Show("value set!"); 
            _students = value;
        }
    }
}