Higher

c# 복습 본문

컴공 복습

c# 복습

Myers 2020. 7. 19. 20:23

진수

 

0b : 2진수 ex) 0b1111_0000 = 240

0x : 16진수ex) 0xF0 = 240

 

int a = int.MaxValue a= 2147483647

a+=1 a= -2147483648

 

2진수

0111111111 a

1000000000 a+1

1000000001 -a

 

decimal 형식 부동소수점보다 느리지만 정확.

 

변환타입

int a = 123; b = a.ToString();

a = "123" b = Convert.ToInt32(a)

a = "1 . 23" b = float.Parse(a)

 

string format

Console.WriteLline({0, 5} x {1, -5} = {2, 10}, i, j, i*j)

_____7 x 1_____=____________7 이런형식으로

 

x8, x2 : 16진수 서식 지정자. 8,2는 최소 자릿수

a=1 b=127

{0:D5} (0X{0:X8})", a << 5

00032 (0X000000020)

 

{0:D5} (0X{0:X2}), (sbyte)((b>>1))

000063 (0X3F)

 

sbyte -128~127

byte 0~255

 

문법

object 타입에 null 대입가능

다른타입에도 넣고 싶다면

int? num = null; 이런식으로 사용

num ?? 0 // numnull이면 0을 대입.

 

stringbyte로 변환하고싶으면

a = (byte)char.Parse(Console.ReadLine());

or

a = (byte)Console.Read();

Console.Read(); //\r (13)

Console.Read(); //\n (10)

 

값 타입 검출

object obj = null;

string s = console.readline();

if(int.TryParse(s, int out out_i))

          obj = out_i

else if(float.TryParse(s, float out out_f))

          obj = out_f

else

          obj = s;

switch(obj){

          case int i:  break;

          default : break;

}

 

foreach 배열/컬렉션 개념

int[] arr = new int[]{0,1,2};

foreach(int a in arr)

console.writeLine(a)

 

무한반복

for(;;) while(true)

do

printf(“...”);

while();

 

""==string

string.isNullOrEmpty(string)

널이거나 비어있으면 true 반환

 

클래스

객체 = 속성(데이터)+기능(메소드)

 

클래스

static 클래스의 인스턴스별로 동작이 아니라 클래스 소속으로 동작

변수

1.Field - Static 클래스수준 접근 -> Data 구역

2.Field - Instance 객체체 수준 접근 -> Heap 구역

3.Local 변수 지역변수 : 해당 메소드 내에서만 접근 -> Stack FILO

 

static 메소드 는 지역변수와 static 변수만 사용 가능

static 메소드 실행 위해서는 class.static변수명() , 클래스 수준에서 호출

 

Swap(x,y)

call by value

static void Swap(int a, int b)

원본 변수 복사하여 메소드 내에서 작용

 

ref

call by reference

static void Swap(ref int a, ref int b)

매개변수가 메소드에 넘겨진 원본 변수 직접 참조

 

out

반드시 원본 변수에 값을 넣어야 할 경우 사용

void Divide(int a, int b, out int quotient, out int remainder)

quotient = a/b

remainder=a%b

Divide(10, 0, out int c, out int d)) 이런식으로 호출

 

메소드 오버로딩시 반환타입은 무관

ex) return (double)(a+b), a+b 상관없이 매개변수 형식 같으면 안됨

 

params 가변길이 매개 변수

int Sum(params int[] args)

int sum=0;

foreach(int a in args)

sum+=a;

 

명명된 매개 변수

static void PrintProfile(string name, string phone){}

Main{ PrintProfile(name : "박찬호", phone : " 234234") }

 

선택적 매개 변수 - 메소드의 매개 변수는 기본값을 가질 수 있음

메소드 오버로딩이랑 같이 쓰기 xx

 

shallow copy : 객체 복사시 참조만 복사

MyClass soruce = new MyClass();

MyClass target = source;

target 소속 변수 바꿔도 source에 변화 없음.

 

deep copy 별도의 힙 공간에 개체 자체 복사

public myClass DeepCopy()

MyClass newCopy = new MyClass();

newCopy.t1 = this.t1;

return newCopy

newCopy.t1 값 변경시

source.t1 값도 변경

 

this()생성자

public MyClass()

this.a = 1;

public MyClass( int b) : this()

this.b = b;

 

접근한정자 Access Modifier : 공개수준 결정

public, protected, private

oop 특성은 inheritance상속성, polymorphism다형성, Encapsulation 은닉성

 

자동 구현 프로퍼티

public string Name{

set;

get;

}

 

프로퍼티 기본값

public string Name { get; set; } = "unknown";

 

배열

형식 데이터형식[ ] 배열이름 = new 데이터형식[ 용량 ];

string[] array1 = new string[3]{“안녕”, “Hello”,“Halo”};

string[] array2 = new String[] {“안녕”, “Hello”,“Halo”};

string[] array3 = {“안녕”, “Hello”,“Halo”};

string[,] array4 = new string[,] {{}{}} //2차원 배열

정적메소드 Clear() //모든요소초기화, ForEach<T>()

인스턴스메소드 GetLength()

프로퍼티 Length//배열 길이 반환 Rank //배열 차원 반환

 

Array.Sort( 배열 )

int[] scores = new int[] { 80, 74, 81, 90, 34 };

Array.Sort(scores);

 

Array.BinarySearch<>(배열, 찾을수);

Console.WriteLine(Array.BinarySearch<int>(scores, 81));

 

Array.IndexOf(배열, 찾을 수);

Console.WriteLine(Array.IndexOf(scores, 81));

 

Array.Resize

Array.Resize<int>(ref scores, 10);

Array.Resize<int>(ref scores, 10);

Dog[] array_dog = new Dog[3];

array_dog[1] = new Dog();

 

2차원배열 출력

int[,] arr3 = { { 1, 2, 3 }, { 4, 5, 6 } };

for (int i = 0; i < arr3.GetLength(0); i++)

{

for (int j = 0; j < arr3.GetLength(1); j++)

{

Console.Write($"[{i},{j}] : {arr3[i, j]} ");

}

Console.WriteLine();

}

 

상속

기반클래스 Base Class (부모클래스)

파생클래스 Derived Class (자식클래스) 파생클래스가 기반클래스 선택

 

수명주기

기반 생성자 -> 파생 생성자 -> 파생 종료자 -> 기반 종료자

 

public Devide() : Base() Base()부터 실행 후 Devide()실행

 

is 연산 : 캐스팅 성공시 true, or false // 오직 캐스팅성공유무만 판단 가능

if(parent is chidren)

 

as 연산 : 캐스팅 성공시 캐스트결과 return , 실패시 null

 

메소드 오버라이딩 (메소드 재정의)

base virtual 메소드를 derived override로 재정의 가능

private 는 재정의 불가

메소드 하이딩

기반클래스의 메소드를 감추고 파생클로스 구현만 표시

class Base

{

public void MyMethod(){}

}

class Derived : Base

{

public new void MyMethod(){}

 

오버라이딩 봉인 // 클래스, 메소드 sealed 로 되있을 시 상속 불가

class Base

{

public void MyMethod(){}

}

class Derived : Base

{

public sealed void MyMethod(){} //sealed 된 클래스 상속 불가

 

private 상속 불가

protected 상속 가능

 

클래스는 한정자 명시x private

 

인터페이스

인터페이스 : 메소드, 이벤트, 인덱서, 프로퍼티만 소유

구현x only 선언

접근 제한 한정자 불가, 모드 public

객체 생성 불가, 자료형으로는 가능(참조)

 

인터페이스 상속 : 클래스 ,인터페이스, 구조체

 

I상속 I : I 수정할수 없을 때, 기존코드에 영향x 기능 추가

 

abstract class 추상 클래스

unlike 인터페이스, 구현을 가질 수 있음

unlike class, 인스턴스(객체)가질 수 x

unlike class , abstract method

 

일반화 프로그래밍

오버로딩 없이 모든 형식 지원

<형식 매개 변수>가 들어감, 호출시<>사이에 T, 대신에 형식이름 입력

메소드일반화

void CpoyArray<T> (T[] source, T[] target){}

 

main(){

int[] source = {1,2,3};

int[] target = {2,3,4};

CopyArray<T>(soure, target);

 

List<T>

class MyList<T>

{

private T[] array;

 

public MyList()

{

array = new T[3];

}

public T this[int index]

{

get { return array[index]; }

set

{

if (index >= array.Length)

{

Array.Resize<T>(ref array, index + 1);

Console.WriteLine($"Array resized :{array.Length}");

}

array[index] = value;

}

}

public int Length

{

get { return array.Length; }

}

}

 

형식매개변수 제약

where T : MyClass // MyClass를 상속받는 형식이어야할 것

 

class StructArray<T> where T : struct {

public T[] Array { get; set; }

public int Length { get; set; }

 

public StructArray(int size) {

Array = new T[size];

Length = size;

}

}

 

class RefArray<T> where T : class {}

main에서

RefArray<StructArray<double>> b = new RefArray<StructArray<double>>(3);

 

파일 쓰기

BinaryWriter : 이진 데이터 기록

BinaryWriter bw = new BinaryWriter( new FileStream(“a.dat”, FileMode.Create) );

bw.Write(int.MaxValue);

bw.Write(“Good Morning!”);

bw.Close();

BinaryReader : 이진 데이터 읽기

BinaryReader br = new BinaryReader( new FileStream(“a.dat”, FileMode.Open));

int a = br.ReadInt32();

string b = br.ReadString();

br.Close();

StreamWriter/ StreamReader

FileStream : 반드시 byte, byte[] 형식으로 입출력해야함.

StreamWriter : 텍스트 데이터 쓰기

StreamWriter sw = new StreamWriter( new FileStream(“a.dat”, FileMode.Create) );

sw.WriteLine(int.MaxValue);

sw.WriteLine(“Good Morning!”);

sw.Close();

StreamReader : 텍스트 데이터 읽기

StreamReader sr = new StreamReader( new FileStream(“a.dat”, FileMode.Open) );

while ( sr.EndOfStream == false ) {

Console.WriteLine(sr.ReadLine());

}

sr.Close();

 

 

BinaryReader br 바이너리 읽기

BinaryWriter bw = new BinaryWriter(new FileStream("a.dat", FileMode.Create));

bw.Write(int.MaxValue);

bw.Write("굿모닝");

bw.Close();

FileStream fs = new FileStream("a.dat", FileMode.Open);

BinaryReader br = new BinaryReader(fs);

Console.WriteLine($"File size : {br.BaseStream.Length} bytes");

Console.WriteLine(br.ReadInt32());

Console.WriteLine(br.ReadString());

Console.WriteLine(br.ReadUInt32());

Console.WriteLine(br.ReadString());

Console.WriteLine(br.ReadDouble());

bw.Close();

 

 

Comments