在循环中创建对象

时间:2014-12-06 19:43:10

标签: c# loops object

我一直在寻找在循环中创建一个新对象,找到一些答案和主题,但它太难理解了。用列表和数组等制作它。

我要做的是,从用户那里获得一个输入(比方说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();
    }
}

我知道我必须使用数组或列表创建对象。但我真的不明白在他们逐个创建之后我将如何访问它们。

6 个答案:

答案 0 :(得分:2)

创建动态类(其中对象的实际名称不同)相当先进。换句话说,与创建List或Array相比,它更难以做你所要求的事情。如果你花一两个小时来学习收藏,那么从长远来看它会得到回报。

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

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

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

答案 1 :(得分:1)

最接近你所要求的是创建一个词典:

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

答案 2 :(得分:0)

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

您需要的是persons

的集合
var persons = new List<person>();

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

答案 3 :(得分:0)

Arrays和List是基本构建块。他们应该很努力。但是如果你不想处理它们,请尝试创建一个方法,该方法的责任是给你新的对象给予计数。

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

答案 4 :(得分:0)

试试这个。

我首先将Person(Object)创建为数组(如创建对象数组)

然后我将其分配给Person Class。

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

答案 5 :(得分:0)

如果要遍历C#中的对象数组,则需要定义ToString()方法(覆盖),然后,可以使用ToString()方法。