【问题标题】:How do i use this class in the main function? Dictionaries and indexers (Collections)我如何在主函数中使用这个类?字典和索引器(集合)
【发布时间】:2013-08-04 15:51:38
【问题描述】:

我正在尝试在字典数组列表中添加条目,但我不知道在主函数的 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 方法 'Add' 没有重载需要 2 个参数

【问题讨论】:

  • 你必须传递你在重载的 Add 方法中定义的参数

标签: c# class collections dictionary


【解决方案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 对象。 people 类方法上的 Add 将负责为您将其添加到字典中,并提供名称(字符串)参数和 Person 参数。

您的Person 类只有一个无参数构造函数,这意味着您需要在setter 中设置您的Name。当您像上面那样实例化对象时,您可以这样做。

【讨论】:

  • 我收到此错误:错误 1 ​​'ProjectName.Person' 不包含采用 1 个参数的构造函数
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多