繁体   English   中英

我如何在main函数中使用这个类? 字典和索引器(集合)

[英]How do i use this class in the main function? Dictionaries and indexers (Collections)

我试图在字典数组列表中添加条目,但我不知道在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个参数

这个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。 您可以在实例化上述对象时执行此操作。

对于您的设计,这将解决问题:

    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;
            }
        }
    }

在主要:

People peop = new People();
peop.Add("Josh", new Person() { Name = "Josh" });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM