C#/수업내용
03/17 배열 변수 선언, 인스턴스 생성, 값 할당, 출력 복습 2
박준희
2021. 3. 17. 10:52
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study06
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Main");
new App();
}
}
}
App.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study06
{
public class App
{
public App()
{
Console.WriteLine("App");
//Item배열 변수 선언
Item[] items;
//Item배열 인스턴스 및 변수에 할당
items = new Item[5];
//Item 객체 생성
Item item1 = new Item(10, "장검");
Item item2 = new Item(11, "단검");
Item item3 = new Item(12, "창");
//Item배열 요소에 값 추가
items[0] = item1;
items[1] = item2;
items[2] = item3;
//Item배열 의 길이 출력
Console.WriteLine("Item배열 의 길이 출력 : " + items.Length);
//for, foreach문을 사용해 Item배열의 요소 출력 (아이템 ID, 아이템 이름)
Console.WriteLine("\nfor문을 사용해 Item배열의 요소 출력 (아이템 ID, 아이템 이름)");
for(int i = 0; i < items.Length; i++)
{
if(items[i] != null)
{
Console.WriteLine("({0}, {1})", items[i].GetId(), items[i].GetName());
}
else
{
Console.WriteLine("empty");
}
}
Console.WriteLine("\nforeach문을 사용해 Item배열의 요소 출력 (아이템 ID, 아이템 이름)");
foreach(Item item in items)
{
if (item != null)
{
Console.WriteLine("({0}, {1})", item.GetId(), item.GetName());
}
else
{
Console.WriteLine("empty");
}
}
}
}
}
Item.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study06
{
public class Item
{
private int id;
private string name;
public Item(int id, string name)
{
this.id = id;
this.name = name;
}
public int GetId()
{
return this.id;
}
public string GetName()
{
return this.name;
}
}
}