C# 기본 - 02
○ Method(함수)
class Program
{
static void MyMethod()
{
// code to be executed
}
}
함수 생성 및 호출
static void MyMethod()
{
Console.WriteLine("I just got executed!");
}
static void Main(string[] args)
{
MyMethod();
}
// Outputs "I just got executed!"
함수 내에 매개변수 >> 여러 개의 매개변수도 가능함. 쉼표로 구분
매개변수 값을 fname = "John" 으로 하면 기본값으로 John이 사용됨
static void MyMethod(string fname)
{
Console.WriteLine(fname + " Refsnes");
}
static void Main(string[] args)
{
MyMethod("Liam");
MyMethod("Jenny");
MyMethod("Anja");
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
값을 반환하는 함수
void 대신 데이터 타입 int / double 사용 , return 통해 값 반환
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
}
// Outputs 8 (5 + 3)
○ Class / Object
C#은 객체지향언어
Car라는 class 와 myobj라는 Object 생성에 대한 예시
>> 하나의 클래스 안에 여러 개의 객체 생성 가능
>> A 클래스에서 B 클래스의 객체를 생성하여 사용할 수 있음
class Car
{
string color = "red";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.color);
}
}
클래스 내의 변수를 필드라고 한다. (color , maxSpeed)
이는 값을 지정할 수도 있고 아래처럼 값 없이 선언 후 객체를 생성할 때 값을 지정할 수도있다.
class Car
{
string color;
int maxSpeed;
static void Main(string[] args)
{
Car myObj = new Car();
myObj.color = "red";
myObj.maxSpeed = 200;
Console.WriteLine(myObj.color);
Console.WriteLine(myObj.maxSpeed);
}
}
아래와 같이 여러 개의 객체에서 필드를 사용할 수 있다.
class Car
{
string model;
string color;
int year;
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
클래스 내부에 함수를 생성하여 해당 함수를 실해
class Car
{
string color; // field
int maxSpeed; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
static void Main(string[] args)
{
Car myObj = new Car();
myObj.fullThrottle(); // Call the method
}
}
생성자
- 객체를 초기화하는데 사용되는 메서드 , 클래스의 객체가 생성될 때 호출된다.
- 필드의 초기값을 설정하는데 사용할 수 있다.
- 클래스 이름과 일치해야한다.
- 매개변수 사용 가능하다.
// Create a Car class
class Car
{
public string model; // Create a field
// Create a class constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}
static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}
// Outputs "Mustang"
○ Access Modifiers
public : 모든 클래스 접근 가능
private : 같은 클래스 내에서만 접근 가능
protected : 같은 클래스 또는 상속받은 클래스에서만 접근 가능
internal : 같은 어셈블리(하나의 파일) 내에서는 접근이 가능하지만 다른 어셈블리에서는 접근할 수 없도록 하는 방법
○ Get & Set
private 변수일때 외부 클래스에서 접근하는 방법 중 하나
get : 변수의 값 반환
set : 변수에 값을 할당함
class Person
{
private string name; // field
public string Name // property
{
get { return name; }
set { name = value; }
}
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
>> 이에 대한 필드를 정의할 필요없이 간단하게 작성 가능함
class Person
{
public string Name // property
{ get; set; }
}
class Program
{
static void Main(string[] args)
{
Person myObj = new Person();
myObj.Name = "Liam";
Console.WriteLine(myObj.Name);
}
}
○ 상속
자식 : 부모 로 상속
이는 코드 재사용에 유용함
다른 클래스가 상속하지 않도록 하려면 sealed class로 만들면 된다.
class Vehicle // base class (parent)
{
public string brand = "Ford"; // Vehicle field
public void honk() // Vehicle method
{
Console.WriteLine("Tuut, tuut!");
}
}
class Car : Vehicle // derived class (child)
{
public string modelName = "Mustang"; // Car field
}
class Program
{
static void Main(string[] args)
{
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (From the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand field (from the Vehicle class) and the value of the modelName from the Car class
Console.WriteLine(myCar.brand + " " + myCar.modelName);
}
}
부모와 자식 클래스에서 생성한 함수의 이름이 같은경우 , 객체를 생성하여 해당 함수를 호출하면 부모 클래스의 함수만 호출된다.
이럴때는 부모 클래스의 함수에 virtual , 자식 클래스의 함수에 override 키워드를 추가하면 된다.
class Animal // Base class (parent)
{
public virtual void animalSound()
{
Console.WriteLine("The animal makes a sound");
}
}
class Pig : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
class Dog : Animal // Derived class (child)
{
public override void animalSound()
{
Console.WriteLine("The dog says: bow wow");
}
}
class Program
{
static void Main(string[] args)
{
Animal myAnimal = new Animal(); // Create a Animal object
Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object
myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound();
}
}
○ Abstract 추상 클래스/함수
추상 클래스 : 객체를 생성하는데 사용할 수 없는 제한된 클래스 ( 다른 클래스에서 상속되어야 접근 가능 )
추상 함수 : 추상 클래스에서만 사용할 수 있으며 본문이 없음 ( 파생(자식) 클래스에 의해 제공됨)
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
// Derived class (inherit from Animal)
class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); // Call the abstract method
myPig.sleep(); // Call the regular method
}
}
interface : 추상 클래스이며 추상 함수와 속성만 포함할 수 있음 ( 필드 포함할 수 없음 )
// Interface
interface IAnimal
{
void animalSound(); // interface method (does not have a body)
}
// Pig "implements" the IAnimal interface
class Pig : IAnimal
{
public void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
class Program
{
static void Main(string[] args)
{
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
}
}
○ 열거형 (enum)
기본적으로 첫번째 항목은 0을 갖고 그 이후로는 1씩 증가하는 값을 갖는다.
enum Months
{
January, // 0
February, // 1
March, // 2
April, // 3
May, // 4
June, // 5
July // 6
}
static void Main(string[] args)
{
int myNum = (int) Months.April;
Console.WriteLine(myNum);
}
Switch문에 사용할 수 있음
enum Level
{
Low,
Medium,
High
}
static void Main(string[] args)
{
Level myVar = Level.Medium;
switch(myVar)
{
case Level.Low:
Console.WriteLine("Low level");
break;
case Level.Medium:
Console.WriteLine("Medium level");
break;
case Level.High:
Console.WriteLine("High level");
break;
}
}
○ 파일 작업
using System.IO; // include the System.IO namespace
File.SomeFileMethod(); // use the file class with methods
< 파일 관련 함수 >
AppendText() : 파일의 제일 마지막에 text 추가
Copy() : 파일 복사
Create() : 파일 생성
Delete() : 파일 삭제
Exists() : 파일이 존재하는지 확인
ReadAllText() : 파일 내부 내용 출력(읽음)
Replace() : 해당 파일의 내용을 다른 바일의 내용으로 대체
WriteAllText() : 새로운 파일을 생성하고 내용 입력
아래 코드를 통해 파일에 내용을 입력할 수 있고 파일의 내용을 조회(출력)할 수도 있다.
using System.IO; // include the System.IO namespace
string writeText = "Hello World!"; // Create a text string
File.WriteAllText("filename.txt", writeText); // Create a file and write the content of writeText to it
string readText = File.ReadAllText("filename.txt"); // Read the contents of the file
Console.WriteLine(readText); // Output the content
○ 예외 처리
try
{
// Block of code to try
}
catch (Exception e)
{
// Block of code to handle errors
}
결과에 관계없이 finally 코드는 실행됨
try
{
int[] myNumbers = {1, 2, 3};
Console.WriteLine(myNumbers[10]);
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.");
}
finally
{
Console.WriteLine("The 'try catch' is finished.");
}
throw를 통해 사용자 정의 오류 생성 가능함
throw 뒤에 올 수 있는 예외 클래스들에는 ArithmeticException , FileNotFoundException..등이 있음
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else
{
Console.WriteLine("Access granted - You are old enough!");
}
}
static void Main(string[] args)
{
checkAge(15);
}