实例化类赋予该名称不存在

问题描述 投票:-2回答:2

我正在尝试通过创建一个小程序来学习OOP,该程序读取人员列表并仅使用两个类Person和PollParticipant输出30岁以上的人。我正在从我的人类中实例化一个新人并添加名称和年龄: Person person = new Person(name,age);,它们是在构造函数中定义的,但是当我这样做时它给了我一个错误,即the name 'name' does not exist in the current context。我的字段设置为公开,因此它应该能够访问它们,我做错了什么?

这是我的Person类:

namespace Poll_Opinion
{
    public class Person
    {
        public string name;
        public int age;

        public Person(string name, int age)
        {
            this.name = Name;
            this.age = Age;
        }

        public string Name
        {
            get
            {
                return this.name;
            }

            set
            {
                this.name = value;
            }
        }
        public int Age
        {
            get
            {
                return this.age;
            }

            set
            {
                this.age = value;
            }
        }
    }
}

我的投票参与者课程:

namespace Poll_Opinion
{
    class PollParticipant
    {
        public List<Person> pollParticipant;

        public PollParticipant()
        {
            this.pollParticipant = new List<Person>();
        }

        public void AddMember(Person participant)
        {
            this.pollParticipant.Add(participant);
        }

        public Person ShowOlderMembers()
        {
            return this.pollParticipant.OrderByDescending(p => p.age).First();

        }

    }
}

我的Program.cs我在那里进行实例化:

namespace Poll_Opinion
{
    class Program
    {

        static void Main(string[] args)
        {


            PollParticipant pollparticipant = new PollParticipant();

            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                string[] input = Console.ReadLine().Split();
                int age = int.Parse(input[i]);

                Person person = new Person(name,age);
                pollparticipant.AddMember(person);
            }
        }
    }
}
c#
2个回答
1
投票

你有两个问题。第一个是:

Person person = new Person(name,age);

你试图将nameage传递给Person构造函数,但是你还没有实例化它们。

第二个问题出在你的构造函数中:

public Person(string name, int age)
{
    // this.name = Name;
    this.name = name;
    // this.age = Age;
    this.age = age;
}

您需要将name参数分配给this.name字段,而不是Name属性。在你的情况下,你将this.name分配给this.name

this.name = Name; // => where 'Name' get method return this.name

public string Name
{
    get
    {
        return this.name;
    }
    set
    {
        this.name = value;
    }
}

顺便说一句,在这种情况下,您不需要公共字段name(应该是私有的)。做就是了:

public string Name { get; set; }

在C#中,属性实际上已经有一个隐藏的私有字段。


0
投票

在创建Person对象时,未在Main()函数中定义name

© www.soinside.com 2019 - 2024. All rights reserved.