[英]C# objects and arrays, how to use them?
Hello all I am working on a project for my C# class and am a bit confused I am trying to add objects to an array and then print them to the console to see if they are there but this is not working for me I am completely lost can someone perhaps show me how to go about this code below.大家好,我正在为我的 C# 类开发一个项目,有点困惑我正在尝试将对象添加到数组,然后将它们打印到控制台以查看它们是否在那里,但这对我不起作用我完全迷失了有人可以告诉我如何处理下面的代码。
using System;
class CreateTaxPayer
{
static void Main()
{
Taxpayer[] testArray = new Taxpayer[1];
for (int i = 0; i < testArray.Length; i++)
{
Console.Write("Enter the social security number for taxpayer" + (i + 1) + " ");
testArray[i].SSN = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(testArray[i].SSN);
}
}
}
class Taxpayer
{
public int SSN { get; set; }
}
You are creating the array, but you also have to create the elements of the array.您正在创建数组,但您还必须创建数组的元素。 Like this:像这样:
testArray[i] = new Taxpayer();
testArray[i].SSN = Convert.ToInt32(Console.ReadLine());
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Taxpayer[] testArray = new Taxpayer[1];
for (int i = 0; i <testArray.Length; i++)
{
Console.Write("Enter the social security number for taxpayer" + (i + 1) + " ");
testArray[i] = new Taxpayer();
testArray[i].SSN = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(testArray[i].SSN);
}
}
}
class Taxpayer
{
public int SSN { get; set; }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.