实例化类表明该名称不存在

时间:2019-04-18 14:56:38

标签: c#

我正在尝试通过创建一个小型程序来学习OOP,该程序读取人员列表并使用Person和PollParticipantant两个类仅输出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);
            }
        }
    }
}

2 个答案:

答案 0 :(得分: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#中,这些属性实际上已经具有一个隐藏的私有字段。

答案 1 :(得分:0)

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

name