C#控制台程序索引器仅查找我列表中的第一项<&燃气轮机;
下面是一个包含三个类的非常基本的程序,它使用索引器根据年龄在每个列表中搜索一个人 Person.cs如下:C#控制台程序索引器仅查找我列表中的第一项<&燃气轮机;,c#,indexer,C#,Indexer,下面是一个包含三个类的非常基本的程序,它使用索引器根据年龄在每个列表中搜索一个人 Person.cs如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Indexer1 { public class Person { private string name; private string surnam
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Indexer1
{
public class Person
{
private string name;
private string surname;
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public override string ToString()
{
return string.Format("{0} {1} {2}", name, surname, age);
}
public Person(string name, string surname, int age)
{
this.name = name;
this.surname = surname;
this.age = age;
}
}
}
Indexer.cs根据以下内容实例化列表中的人员:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Indexer1
{
public class Indexer
{
List<Person> per = new List<Person>();
public Indexer()
{
per.Add(new Person("Joe", "Soap", 25));
per.Add(new Person("Marry", "Jane", 82));
per.Add(new Person("Garry", "Zuma", 37));
per.Add(new Person("Nelson", "Mabaso", 14));
}
public Person this[int indexes]
{
get
{
foreach (Person item in per)
{
if (item.Age == indexes)
{
return item;
}
else
{
return null;
}
}
return null;
}
set
{
per[indexes] = value;
}
}
}
}
当我运行程序并通过输入他的年龄(25岁)搜索每个“Joe Soap”添加到列表中的第一个人时,当出现提示时,我能够成功地找到他并显示他的所有信息
但是,只要我搜索列表中的其他人,比如说“Garry Zuma”,输入他的年龄:37岁,当出现提示时,程序失败并抛出异常:
Indexer1.exe中发生“System.NullReferenceException”类型的未处理异常
其他信息:对象引用未设置为对象的实例。
我曾尝试搜索该异常,但找不到任何解决问题的方法
非常感谢您的帮助和帮助。查看迭代过程。考虑到在第一次迭代中,<代码>如果(It.Acth==index)被评估为<代码> false ,那么该方法将返回<代码> null <代码>到调用方法(跳过迭代的其余部分)。因此,您需要做的是,删除
else{..}
部分;因此,如果满足条件,方法将返回Person
对象,否则将在迭代后返回null
public Person this[int indexes]
{
get
{
bool isFound = false;
foreach (Person item in per)
{
if (item.Age == indexes)
{
return item;
}
}
return null;
}
set
{
per[indexes] = value;
}
}
您需要从索引器中删除以下代码
else
{
return null;
}
该代码防止循环通过列表中的第一项在调试器中运行程序,并逐步查看程序正在执行的操作。除此之外,现在是了解自动实现的属性的好时机。要展开,
private int;public int Age{get{return Age;}set{Age=value;}}
可以是public int Age{get;private set;}
。希望这能激励我去了解他们。嗨,伙计们,我可能应该提到我是c#的新手。现在来看,这是我遇到的一个非常简单的问题。但是我非常感谢你的建议!:-)@克丽丝:但是私人变量!=私人电视台。难道不应该是public int{get;set;}
?我已经在这个答案中格式化了代码,请为下一次正确格式化帖子。非常感谢。
else
{
return null;
}