[英]How do i use this class in the main function? Dictionaries and indexers (Collections)
I am trying to add entries in dictionary array list but i don't know which arguments to set in the People Class in the main function. 我试图在字典数组列表中添加条目,但我不知道在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;
}
}
}
using this seem to give me error 使用这似乎给我错误
static void Main(string[] args)
{
People peop = new People();
peop.Add("Josh", new Person("Josh"));
}
Error 2 No overload for method 'Add' takes 2 arguments 错误2方法“添加”没有重载需要2个参数
This peop.Add("Josh", new Person("Josh"));
这个
peop.Add("Josh", new Person("Josh"));
should be this 应该是这个
var josh = new Person() // parameterless constructor.
{
Name = "Josh" //Setter for name.
};
peop.Add(josh);//adds person to dictionary.
The class People
has the method Add which only takes one argument: a Person object. People
类具有Add方法,它只接受一个参数:一个Person对象。 The Add on the people class method will take care of adding the it to the dictionary for you and supplying both the name (string) argument and the Person argument. Add on the people类方法将负责将它添加到字典中,并提供name(string)参数和Person参数。
Your Person
class only has a parameterless constructor, which means that you need to set your Name in the setter. 您的
Person
类只有一个无参数构造函数,这意味着您需要在setter中设置Name。 You can do this when you instantiate the object like above. 您可以在实例化上述对象时执行此操作。
For your design this would solve the problem: 对于您的设计,这将解决问题:
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;
}
}
}
And in Main: 在主要:
People peop = new People();
peop.Add("Josh", new Person() { Name = "Josh" });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.