我正在尝试在字典数组列表中添加条目,但我不知道在main函数的People类中设置哪些参数。
public class People : DictionaryBase
{
public void Add(Person newPerson)
{
Dictionary.Add(newPerson.Name, newPerson);
}
public void Remove(string name)
{
Dictionary.Remove(name);
}
public Person this[string name]
{
get
{
return (Person)Dictionary[name];
}
set
{
Dictionary[name] = value;
}
}
}
public class Person
{
private string name;
private int age;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
}
使用这似乎给我错误
static void Main(string[] args)
{
People peop = new People();
peop.Add("Josh", new Person("Josh"));
}
错误2方法“添加”没有重载需要2个参数
答案 0 :(得分:1)
这peop.Add("Josh", new Person("Josh"));
应该是这个
var josh = new Person() // parameterless constructor.
{
Name = "Josh" //Setter for name.
};
peop.Add(josh);//adds person to dictionary.
类People
的方法是Add,它只接受一个参数:一个Person对象。 Add on the people类方法将负责将它添加到字典中,并提供name(string)参数和Person参数。
您的Person
类只有一个无参数构造函数,这意味着您需要在setter中设置Name。您可以在实例化上述对象时执行此操作。
答案 1 :(得分:1)
对于您的设计,这将解决问题:
public class People : DictionaryBase
{
public void Add(string key, Person newPerson)
{
Dictionary.Add(key , newPerson);
}
public void Remove(string name)
{
Dictionary.Remove(name);
}
public Person this[string name]
{
get
{
return (Person)Dictionary[name];
}
set
{
Dictionary[name] = value;
}
}
}
public class Person
{
private string name;
private int age;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
}
在Main:
People peop = new People();
peop.Add("Josh", new Person() { Name = "Josh" });