
Console.ReadLine().Split(' '); // 공백 기준으로 입력값을 나눈다
입력을 4 5 이런 식으로 입력할 수 있다.
클래스, 객체
● 가상 메서드 (virtual)
virtual 키워드를 사용하여 선언되며, 자식 클래스에서 필요에 따라 재정의될 수 있다.● 오버라이딩 (Overriding)
virtual: 가상의실형태가 다를 수 있으니 실형태에 재정의가 되어있는지 확인해라
public class Unit
{
public virtual void Move() // 자식이 재정의 했을 수도 있다.
{
Console.WriteLine("두발로 걷기");
}
}
public class Marine : Unit
{
}
public class Zergling : Unit
{
public override void Move() // 자식 클래스에서 재정의
{
Console.WriteLine("네발로 걷기");
}
}
static void Main(string[] args)
{
List<Unit> list = new List<Unit>();
list.Add(new Marine());
list.Add(new Zergling());
foreach (var unit in list)
{
unit.Move();
}
}
출력
두발로 걷기
네발로 걷기 (virtual이 없으면 두발로 걷기 출력)
● 추상(Abstract) 클래스와 메서드
abstract 키워드를 사용하여 선언되며, 추상 메서드를 포함할 수 있다.abstract class Shape
{
public abstract void Draw();
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a Circle");
}
}
static void Main(string[] args)
{
List<Shape> list = new List<Shape>();
list.Add(new Circle());
foreach (Shape shape in list)
{
shape.Draw();
}
}
출력
Drawing a Circle
● out, ref 키워드
★ out은 매개변수가 메서드 내에서 무조건 값을 할당해야 함
★ ref는 값이 바뀔 수도 있고 안 바뀔 수도 있다.
// out 키워드 사용 예시
static void Divide(int a, int b, out int quotient, out int remainder)
{
quotient = a / b;
remainder = a % b;
}
// ref 키워드 사용 예시
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
// out 키워드 사용 예시
int quotient, remainder;
Divide(7, 3, out quotient, out remainder);
Console.WriteLine($"{quotient}, {remainder}");
// ref 키워드 사용 예시
int x = 1, y = 2;
Swap(ref x, ref y);
Console.WriteLine($"{x}, {y}");
}
출력
2, 1
2, 1