在循环中创建对象
本文关键字:创建对象 循环 | 更新日期: 2023-09-27 18:33:18
我一直在寻找在循环中创建一个新对象,找到了一些答案和主题,但它太难理解了。使用列表和数组等制作它。
我正在尝试做的是从用户那里获取输入(假设 3),并使用唯一名称创建尽可能多的对象。如新人1,新人2,新人3等。
我的代码如下所示:
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();
}
}
我知道我必须使用数组或列表创建对象。但我真的不明白在逐人创建它们之后我将如何访问它们。
创建动态类(对象的实际名称不同)相当高级。换句话说,做你要求的事情比创建一个列表或数组要困难得多。如果您花一两个小时学习收藏,从长远来看,它会得到回报。
此外,您可以考虑向 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);
}
最接近执行您要求的事情是创建一个字典:
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;
}
}
}
您可以在 C#
中创建动态命名的变量。
您需要的是persons
的集合:
var persons = new List<person>();
for (int i = 0; i < p; i++)
{
persons.Add(new person());
}
数组和列表是基本的构建块。 他们不应该很难。 但是,如果您不想处理它们,请尝试创建一个方法,其职责是为您提供给定计数的新对象。
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 };
}
}
试试这个。
我首先创建人(对象)作为数组(就像创建对象数组一样)
然后我将其分配给 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();
}
}
如果要
在 C# 中循环访问对象数组,则需要定义 ToString()
方法(重写),然后可以使用 ToString()
方法。