在循环中创建对象

5

我一直在搜索如何在循环内创建新对象,找到了一些答案和主题,但是理解起来太难了。需要使用列表和数组等。

我想要做的是,从用户那里获取一个输入(比如3),并创建尽可能多的具有唯一名称的对象。比如newperson1、newperson2、newperson3等。

我的代码看起来像这样:

class person
{
}

class Program
{
    static void Main(string[] args)
    {
        Console.Write("How many persons you want to add?: ");
        int p = int.Parse(Console.ReadLine());

        for (int i = 0; i < p; i++)
        {
            person newperson = new person();
        }
    }
}

有没有办法在对象名称末尾创建以下数字的新对象? 谢谢!
编辑: 我的新代码看起来像这样;我更多地是这样思考的:
class Persons
{
    //Person object id
    public int id { get; set; }

    //Persons name
    public string name { get; set; }

    //Persons adress
    public string adress { get; set; }     

    //Persons age
    public int age { get; set; }

    }

class Program
{
    static void Main(string[] args)
    {
        Console.Write("How many persons you want to add?: ");
        int count = int.Parse(Console.ReadLine());

        var newPersons = new List<Persons>(count);

        for (int i = 0; i < count; i++)
        {
            newPersons[i].id = i;

            Console.Write("Write name for person " + i);
            newPersons[i].name = Console.ReadLine();

            Console.Write("Write age for person " + i);
            newPersons[i].age = int.Parse(Console.ReadLine());

            Console.Write("Write adress for person " + i );
            newPersons[i].adress = Console.ReadLine();

        }

        Console.WriteLine("\nPersons \tName \tAge \tAdress");
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine("\t" + newPersons[i].name + "\t" + newPersons[i].age + "\t" + newPersons[i].adress);
        }

        Console.ReadKey();
    }
}

我知道我必须使用数组或列表来创建对象。但是我并不完全明白在逐个创建后如何访问它们。


请使用大驼峰命名法来命名类名,例如class Person - Jonathon Reinhart
此外,您需要一个数组或列表。这并不是“太难”,而是通过使用同类对象的集合来编程,而不是给它们不同的名称。 - Jonathon Reinhart
1
你想要实现什么?列表和数组是编程的基本概念,理解和使用起来不应该很困难。 - Fedor
你计划用你创建的对象做什么?这将决定如何创建它们。 - John Saunders
我正在尝试创建对象作为人。 (用户将选择有多少个对象/人)。 然后用户将为这些人命名并为他们编写地址和年龄。 - onurelibol
显示剩余2条评论
6个回答

7

创建动态类(对象的实际名称不同)相当复杂。换句话说,要做你所要求的比创建一个列表或数组要困难得多。如果你花费一两个小时学习集合,它将在长期内得到回报。

此外,您可以考虑为您的Person类添加Name属性,然后您可以为每个创建的人设置不同的名称。

正如其他人所说,您需要将它们存储在数组或列表中:

public class Person
{
    public string Name { get; set; }
}

static void Main(string[] args)
{
    Console.Write("How many persons you want to add?: ");
    int p = int.Parse(Console.ReadLine());

    var people = new List<Person>();

    for (int i = 0; i < p; i++)
    {
        // Here you can give each person a custom name based on a number
        people.Add(new Person { Name = "Person #" + (i + 1) });
    }
}

以下是访问列表中的一个 Person 并允许用户更新信息的示例。请注意,我已经向 Person 类添加了一些属性:
public class Person
{
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Address { get; set; }
    public int Age
    {
        // Calculate the person's age based on the current date and their birthday
        get
        {
            int years = DateTime.Today.Year - DateOfBirth.Year;

            // If they haven't had the birthday yet, subtract one
            if (DateTime.Today.Month < DateOfBirth.Month ||
                (DateTime.Today.Month == DateOfBirth.Month && 
                 DateTime.Today.Day < DateOfBirth.Day)) 
            {
                years--;
            }

            return years;
        }
    }
}

private static void GenericTester()
{
    Console.Write("How many persons you want to add?: ");
    string input = Console.ReadLine();
    int numPeople = 0;

    // Make sure the user enters an integer by using TryParse
    while (!int.TryParse(input, out numPeople))
    {
        Console.Write("Invalid number. How many people do you want to add: ");
        input = Console.ReadLine();
    }

    var people = new List<Person>();

    for (int i = 0; i < numPeople; i++)
    {
        // Here you can give each person a custom name based on a number
        people.Add(new Person { Name = "Person" + (i + 1) });
    }

    Console.WriteLine("Great! We've created {0} people. Their temporary names are:", 
        numPeople);

    people.ForEach(person => Console.WriteLine(person.Name));

    Console.WriteLine("Enter the name of the person you want to edit: ");
    input = Console.ReadLine();

    // Get the name of a person to edit from the user
    while (!people.Any(person => person.Name.Equals(input, 
        StringComparison.OrdinalIgnoreCase)))
    {
        Console.Write("Sorry, that person doesn't exist. Please try again: ");
        input = Console.ReadLine();
    }

    // Grab a reference to the person the user asked for
    Person selectedPerson = people.First(person => person.Name.Equals(input, 
        StringComparison.OrdinalIgnoreCase));

    // Ask for updated information:
    Console.Write("Enter a new name (or press enter to keep the default): ");
    input = Console.ReadLine();
    if (!string.IsNullOrWhiteSpace(input))
    {
        selectedPerson.Name = input;
    }

    Console.Write("Enter {0}'s birthday (or press enter to keep the default) " + 
        "(mm//dd//yy): ", selectedPerson.Name);
    input = Console.ReadLine();
    DateTime newBirthday = selectedPerson.DateOfBirth;

    if (!string.IsNullOrWhiteSpace(input))
    {
        // Make sure they enter a valid date
        while (!DateTime.TryParse(input, out newBirthday) && 
            DateTime.Today.Subtract(newBirthday).TotalDays >= 0)
        {
            Console.Write("You must enter a valid, non-future date. Try again: ");
            input = Console.ReadLine();
        }
    }
    selectedPerson.DateOfBirth = newBirthday;


    Console.Write("Enter {0}'s address (or press enter to keep the default): ", 
        selectedPerson.Name);

    input = Console.ReadLine();
    if (!string.IsNullOrWhiteSpace(input))
    {
        selectedPerson.Address = input;
    }

    Console.WriteLine("Thank you! Here is the updated information:");
    Console.WriteLine(" - Name ............ {0}", selectedPerson.Name);
    Console.WriteLine(" - Address ......... {0}", selectedPerson.Address);
    Console.WriteLine(" - Date of Birth ... {0}", selectedPerson.DateOfBirth);
    Console.WriteLine(" - Age ............. {0}", selectedPerson.Age);
}

2

最接近您所要求的做法是创建一个字典:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var dictionary = new Dictionary<string, Person>();

        Console.Write("How many persons you want to add?: ");
        int p = int.Parse(Console.ReadLine());

        for (int i = 0; i < p; i++)
        {
            dictionary.Add("NewPerson" + i, new Person());
        }

        // You can access them like this:
        dictionary["NewPerson1"].Name = "Tim Jones";
        dictionary["NewPerson2"].Name = "Joe Smith";
    }

    public class Person
    {
        public string Name {
            get; 
            set;
        }
    }
}

记住原帖中说过,数组“太难了”。我不认为引入字典会有任何帮助。 - Jonathon Reinhart
@JonathonReinhart - 是的,但正如您在上面的评论中指出的那样,它们并不是“太难”。它们是基础。 - Icemanind

1

你可以在 C# 中创建动态命名的变量。

你需要的是一个 persons 集合:

var persons = new List<person>();

for (int i = 0; i < p; i++)
{
   persons.Add(new person());
}

2
@Christos 技术上讲,你可以在 C# 中创建动态程序集、类和方法。但在这种情况下并不值得提及,因为它只会引起混乱。 - Selman Genç

0
如果你想在C#中遍历一个对象数组,你需要定义ToString()方法(重写),之后你就可以使用ToString()方法了。

0

数组和列表是基本构建块,它们不应该很难。但如果你不想处理它们,请尝试创建一个方法,其责任是在给定计数的情况下为您提供新对象。

static void Main(string[] args)
    {
        Console.Write("How many persons you want to add?: ");
        int p = int.Parse(Console.ReadLine());

        var newPersons = CreatePersons(p);

         foreach (var person in newPersons)
         {
             Console.WriteLine("Eneter age for Person :" person.Name);
             person.Age = Console.ReadLine();
         }

    }

    static IEnumerable<Person> CreatePersons(int count)
    {
        for (int i = 0; i < count; i++)
        {
            yield return new Person{ Name="newPerson" +1 };
        }
    } 

0

试试这个。

我首先将 Person(对象)创建为数组(就像创建对象数组一样)。

然后我将其分配给 Person 类。

class Persons
{
    //Person object id
    public int id { get; set; }
    //Persons name
    public string name { get; set; }

    //Persons adress
    public string adress { get; set; }
    //Persons age
    public int age { get; set; }

}

class Program
{
    static void Main(string[] args)
    {
        Console.Write("How many persons you want to add?: ");
        int count = int.Parse(Console.ReadLine());
        //var newPersons = new List<Persons>(count);
        Persons[] newPersons = new Persons[count];

        for (int i = 0; i < count; i++)
        {
            newPersons[i] = new Persons();
            newPersons[i].id = i+1;
            Console.Write("Write name for person " + (i+1) + "\t");
            newPersons[i].name = Console.ReadLine();
            Console.Write("Write age for person " + (i + 1) + "\t");
            newPersons[i].age = int.Parse(Console.ReadLine());
            Console.Write("Write adress for person " + (i + 1) + "\t");
            newPersons[i].adress = Console.ReadLine();
        }

        Console.WriteLine("\nPersons Name \tAge \tAdresss \n");
        for (int i = 0; i < count; i++)
        {
            Console.WriteLine(newPersons[i].name + "\t\t" + newPersons[i].age + "\t" + newPersons[i].adress);
        }

        Console.ReadKey();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接