为什么我的索引器不工作?
Why my Indexer is not working?
Indexers allow instances of a class or struct to be indexed just like
arrays. Indexers resemble properties except that their accessors take
parameters.
我有这样的代码
class StudentMemento
{
Student student;
public Student this[int index]
{
get { return student; }
set { student = new Student { time = DateTime.Now }; }
}
}
class Client
{
static void Main()
{
StudentMemento s = new StudentMemento();
Student s1 = s[1];
Student s2 = s[2];
Student s3 = s[1];
Console.Read();
}
}
根据 msdn 中的文档,我应该在以下成员 s1、s2 中获取 Student 的实例,因为我在 Indexer 中返回 Student 的对象,但我得到的是空引用。任何人都可以帮助我理解,为什么会这样。谢谢
之后
StudentMemento s = new StudentMemento();
s.student 将是 null
。 student
字段仅在索引器 setter 中分配,因此您需要在调用 getter 之前调用它,例如
StudentMemento s = new StudentMemento();
s[1] = null;
Student s1 = s[1];
Student s2 = s[2];
Student s3 = s[1];
Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
我有这样的代码
class StudentMemento
{
Student student;
public Student this[int index]
{
get { return student; }
set { student = new Student { time = DateTime.Now }; }
}
}
class Client
{
static void Main()
{
StudentMemento s = new StudentMemento();
Student s1 = s[1];
Student s2 = s[2];
Student s3 = s[1];
Console.Read();
}
}
根据 msdn 中的文档,我应该在以下成员 s1、s2 中获取 Student 的实例,因为我在 Indexer 中返回 Student 的对象,但我得到的是空引用。任何人都可以帮助我理解,为什么会这样。谢谢
之后
StudentMemento s = new StudentMemento();
s.student 将是 null
。 student
字段仅在索引器 setter 中分配,因此您需要在调用 getter 之前调用它,例如
StudentMemento s = new StudentMemento();
s[1] = null;
Student s1 = s[1];
Student s2 = s[2];
Student s3 = s[1];