Machineboy空

C# Class 기초,필드, 메소드, 멤버, 접근자, 생성자, 예제 등 본문

언어/C#

C# Class 기초,필드, 메소드, 멤버, 접근자, 생성자, 예제 등

안녕도라 2025. 1. 16. 16:48

Class의 개념

The primary object-oriented construct

기초적인 객체 지향 구조(?)

 

a combination of data(field) and behavior(methods).

fields and methods of a class = members

 


Class의 Member 접근자

Access to members can be restricted through access modifier

  • public : member can be accessed by any code
  • private : member can only be accessed by code in the same class
class Car
{
	// public field in PascalCase
	public int Weight;
    
    // private field in camelCase , prexied with _
    private string _color;
}

Class Instance 생성 : New 생성자

class Car {}

var myCar = new Car();
var yourCar = new Car();

Class 의 Field(data)

  • field는 type을 가지고, class 어디에서나 선언될 수 있다.
  • optionally assign an initial value. 초기값을 정해주지 않으면 default value를 할당한다.
class Car
{
	public int Weight = 2500;
    public int Year;
}

var newCar = new Car();
newCar.Weight;
newCar.Year;	// 0

newCar.Year = 2018;		// 2018

Class 의 Field( behavior)

class CarImporter
{
	private int carsImported;
    
    public void ImportCars(int numberOfCars)
    {
    	_carsImported = _carsImported + numberOfCars;
    }
}

Class 의 생성자(Constructor)

  • 생성자의 목표: goal is to initialize a newly created instance. 새롭게 생성된 인스턴스를 초기화해주기 위한 생성자.
  • 생성자의 파라미터: usually stored as private fields

this 키워드로 호출

class Library
{
	private int books;
    
    public Library()
    {
    	this.books = 10;
    }
}

// 이게 constructor생성자를 호출할 것이다.
var library = new Library();

 

class Building
{
	private int numberOfStories;
    private int totalHeight;
    
    public Building(int numberOfStories, double storyHeight)
    {
    	this.numberOfStories = numberOfStories;
        this.totalHeight = numberOfStories * storyHeight;
    }
}

var largeBuilding = new Building(55, 6.2)

예제 : NeedForSpeed

https://exercism.org/tracks/csharp/exercises/need-for-speed/edit

 

Exercism

Learn, practice and get world-class mentoring in over 50 languages. 100% free.

exercism.org

using System;

class RemoteControlCar
{
    public int leftBattery = 100;
    public int distanceDriven = 0;
    
    private int speed;
    private int batteryDrain;
    
    public RemoteControlCar(int speed, int batteryDrain)
    {
        this.speed = speed;
        this.batteryDrain = batteryDrain;
    }
    
    public bool BatteryDrained()
    {
        // 배터리가 소모되어 더 이상 사용할 수 없는 상태를 올바르게 반영
        return leftBattery < batteryDrain;
    }

    public int DistanceDriven()
    {
        return distanceDriven;
    }

    public void Drive()
    {
        if (BatteryDrained()) return;

        distanceDriven += speed;
        leftBattery -= batteryDrain;
    }

    public static RemoteControlCar Nitro()
    {
        return new RemoteControlCar(50, 4);
    }
}

class RaceTrack
{
    private int distance;

    public RaceTrack(int distance)
    {
        this.distance = distance;
    }
    
    public bool TryFinishTrack(RemoteControlCar car)
    {
        while (!car.BatteryDrained())
        {
            car.Drive();
        }

        return car.DistanceDriven() >= distance;
    }
}