Home cshap
Post
Cancel

cshap

cshap

도입

  • c++의 연상력과 VB의 평의성을 결합하기 위한 목적으로 개발된 OOP 언어
  • 닷넷 프레임워크에 최적화 되어있음

다운로드

프로젝트 생성

기본구조 파악

  • 컴파일은 무엇인가?
    1. c#으로 작성된 소스 파일을 컴파일
    2. c# 컴파일어에 의해 exe(어플리케이션)나 dll(라이브러리) 파일 생성(어셈블리라고 부름)
      • 어셈블리 안에는 CIL(common intermediate Language)와 메타데이터(meta-data),매니페스트(manifest) 정보가 포함
      • CIL이란 컴퓨터가 해석 가능한 원시 코드가 되지 전 중간 단계의 언어
    3. JIT 컴파일러에 의해 원시코드로 변경
  • 사용메소드
    • Console.Write()
    • Console.WriteLine() - 라인피드 기능 추가

using

1
using System;
  • 네임스페이스를 사용한다는 의미
  • 전체 이름을 참조하지 않고 선언된 네임스페이스 내부 개체들에 접근 가능
  • 자바의 import와 유사
  • 소스에서의 using은 자바의 try-catch-resource와 같이 자원을 회수

namespace

namespace sampleName
  • 네임프세이스는 관련된 구조체, 클래스, 델리게이트, 인터페이스 등을 그룹화 한것
  • java의 패키지와 유사

main

  • 프로그램의 최초의 진입점(entry point)이며 , 반드시 존재
  • 메인 메소드가 시작되면 프로그램이 시작되며, 종료되면 프로그램도 같이 종료

변수

1
자료형 변수명;
  • 값을 담아두는 상자
  • 선언과 함께 초기화 및 여러개 생성 가능
  • 할당하지 않은 변수를 사용하면 오류 발생
1
2
3
자료형 변수명 = 초기값;

자료형 변수명 = 초기값, 변수명 = 초기값, 변수명 = 초기값 ;

기본 자료형

  • 정수 자료형
    • 자료형 앞에 u가 붙으면 unsigned의 줄임말로 음수의 범위만큼 양수의 범위 확장
  • 실수 자료형
  • 접미사 : float(f), decimal(m)
  • 실수 상수의 기본값 : double
  • 문자, 문자열 자료형
    • String == string
    • 문자 비교시 Equals 또는 == 사용 가능
  • 논리 자료형
    • bool == boolean
  • 객체 자료형
    • 최상위 클래스는 object

서식 지정자

1
{인덱스[, 출력 너비][:서식 문자열]}

형식 변환

  • 정수와 실수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System

namespace ConsoleApplicatino1
{
  class Program
  {
    static void main(string[] args)
    {
      int a = 500;
      float b = a; // 자동 형 변환

      Console.WriteLine("a = {0} ,b = {1}", a, b);
       // a = 500, b = 500

      double c = 123.13;
      int d = (int)c; // 명시적 형 변환

      Console.WriteLine("c = {0} ,d = {1}", c, d);
      // c = 123.12, d = 123
    }
  }
}
  • 숫자와 문자
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 500;
            float b = 60.44f;
            string c = a.ToString();
            string d = c.ToString();

            Console.WriteLine("a = {0}, b = {1}, c = {2}, d = {3}", a, b, c, d);

            string e = "123";
            string f = "123.123";
            int g = int.Parse(e);
            float h = float.Parse(f);

            Console.WriteLine("e = {0}, f = {1}, g = {2}, h = {3}", e, f, g, h);

        }

    }
}

상수

1
const 변수타입 변수명;

연산자

수식 연산자

  • +, -, *, /, %

    증감연산자

  • ++, –

    관계연산자

  • <, >, ==, !=, >=, <=

    할당연산자

  • =, +=, -=, *=, /=, %=

    논리연산자

  • && , || , !

    비트연산자

  • &, |, ^

    시프트연산자

  • >>, «

if~else

1
2
3
4
if(조건식){
}else if(){
}else{
}

switch, break

1
2
3
4
5
6
7
8
switch (조건식){
  case 상수 :
    break;  //없으면 예외 발생
  case 상수 :
    break;
  default :
    break;
}

while

1
2
3
while (조건식){

}

do~while

1
2
3
do {

}while (조건식);

for

1
2
3
for(초기식; 조건식; 증감식){

}

foreach

1
2
3
foreach (변수 in 배열 또는 컬렉션){

}

break

  • 루프 탈출

continue

  • 조건 점프

goto, label

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 0;

            while (num < 100)
            {
                if (num == 40)
                {
                    goto EXIT2;
                }
                num++;
            }

        EXIT:
            Console.WriteLine("num = {0}", num);

        }

    }
}

메소드

1
2
3
  [접근 지정자] 반환형식 메소드명(매개변수 목록){

  }

Call by value VS Call by Reference

  • Call by value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            int b = 2;

            Console.WriteLine("a = {0}, b = {1}", a, b);

            Swap(a, b);

            Console.WriteLine("a = {0}, b = {1}", a, b);

        }

        static void Swap(int a , int b)
        {
            int temp = 0;
            temp = a;
            a = b;
            b = temp;

        }


    }
}

  • swap의 아규먼트는 a 변수의 메모리 주소가 아닌, a 변수의 값을 복제한 메모리 주소가 생성

  • Call by Reference

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            int b = 2;

            Console.WriteLine("a = {0}, b = {1}", a, b);

            Swap(ref a, ref b);

            Console.WriteLine("a = {0}, b = {1}", a, b);

        }

        static void Swap(ref int a ,ref int b)
        {
            int temp = 0;
            temp = a;
            a = b;
            b = temp;

        }


    }
}
  • ref 예약어를 이용하여, 해당 메모리 주소값을 넘길수 있음

메소드 오버로딩

  • 시그니처의 차이에 따라 가능

ref

  • 메모리 주소를 넘김

out

  • 변수 초기화를 하지 않고 전달 가능
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            int b;

            Swap(ref a,out b);

            Console.WriteLine("a = {0}, b = {1}", a, b);

        }

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

            b = 100;
            int temp = 0;
            temp = a;
            a = b;
            b = temp;

        }


    }
}

params

  • 개수가 변동적인 파라미터 처리
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("a = {0}", total(1,2,3,4,5,6,7));

        }

        static int total(params int[] a)
        {

            int total = 0;
            foreach(int i in a)
            {
                total += i;
            }
           return total;
        }


    }
}

array

1
자료형[] 배열명 = new 자료형[크기];

System.Array

  • 배열 지원 메소드

다차원 배열

1
자료형[,] 배열명 = new 자료형[, ];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            multiDemetion();
        }


        static void multiDemetion(){
            
            int[,] arr = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };

            for (int i = 0; i < sample.GetLength(0); i++)
            {
                for (int y = 0; y < sample.GetLength(1); y++)
                {
                    if (y != sample.GetLength(1)-1)
                        Console.Write("[" + i + "][" + y + "]");
                    else
                        Console.WriteLine("[" + i + "][" + y + "]");

                }
            }
        }

    }
}

객체(object)

클래스(class)

1
2
3
4
[접근 제한자] class 클래스명
{

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dog dog = new Dog();
            dog.name = "얼룩이";
            dog.gender = "male";
            dog.bark();
        }


    }

    class Dog
    {
        private string _name;
        public string name
        {
            set{_name = value;}
            get{return _name;}
        }
        private string _gender;
        public string gender
        {
            set{_gender = value;}
            get{return _gender;}
        }

        public void bark()
        {
            Console.WriteLine("{0} : 멍{1}", _name , _gender);
        }

    }

}

접근 제한자

|접근제한자 | 설명| |:–|:–| |public| 어디서든 접근 가능| |protected| 파생 클래스에서 접근 가능| |internal| 같은 어셈블리에서만 접근가능| |protected internal| 같은 어셈블리의 파생클래스에서만 접근 가능| |private|클래스 내부에서만 접근 가능|

this

생성자

  • 자바와 같이 아무것도 적지 않으면 기본 생성자가 생성
    1
    
    클래스명 객체명 = new 생성자;
    
1
2
3
4
5
class 클래스명
  [접근 제한자] 클래스명(매개변수)
  {

  }

소멸자

  • GC에 의해 처리되기 전 실행
  • 호출, 상속, 오버로드 불가
1
2
3
4
5
6
7
class 클래스명{
  ~클래스명()
  {

  }

}

상속

  • private 타입은 비상속
1
2
3
4
5
6
7
8
9
class 부모클래스{

}

class 자식 클래스 : 부모 클래스
{

}

sealed

  • 클래스명 앞에 sealed 사용시 상속 불가

set, get

1
2
3
4
5
6
7
8
public class 클래스명{
  public 변수형태 변수
  {
    set{}
    get{}
  }

}

virtual, override

  • 자식 메소드에서 부모 메소드를 재정의 하고자 한다면, 반드시 virtual 키워드를 붙여야만 재정의가 가능
  • private 메서드는 재정의 분가
  • 재정의 하기 위해서는 자식 메서드에서 override 키워드를 붙여 재정의

new

  • 자식클래스에 부모 클래스와 같은 필드가 있을 경우, 발생하는 경고 표시를 제거하기 위한 기능 ( 의도적이라는 표현 강조)

Upcasting and Downcasting

  • Upcasting : 이슈 없음
  • Downcasting : 이슈 발생

Extension Method

  • 기존 클래스를 직접 수정 불가하며 wapper 패턴으로 처리가 불가할 경우, 해당 메소드의 기능을 확장하고 싶은 경우
  • 확장 메소드의 첫번째 매개변수는 this 한정자가 반드시 존재
1
2
3
4
5
6
7
8
9
10
11
namespace 네임스페이스명
{
  public static class 클래스명
  {
    public static 반환형식 메소드명(this 확장대상형식 식별자, 매개변수 ...){
      ...
    }
    ...
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using Extension;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("{0}", 4.Multiplication(2, 3)); // 32
        }


    }

}

namespace Extension
{
    public static class ExtensionMethod
    {
        public static int Multiplication(this int var, int a, int b)
        {
            int result = var;

            for (int i = 0; i < b; i++)
                result *= a;

            return result;
        }
    }
}

partial class

  • 하나의 클래스를 분할
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;

namespace ConsoleApplication1
{
    partial class Nested
    {
        public void Test() { Console.WriteLine("Test()"); }
    }
    partial class Nested
    {
        public void Test2() { Console.WriteLine("Test2()"); }
    }
    partial class Nested
    {
        public void Test3() { Console.WriteLine("Test3()"); }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Nested nested = new Nested();
            nested.Test();
            nested.Test2();
            nested.Test3();
        }
    }
}

Nested class

  • 클래스 내부에 클래스를 구현
    1
    2
    3
    4
    5
    6
    
    class 클래스명
    {
    class 클래스명
    {
    }
    }
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;

namespace ConsoleApplication1
{
    public class OuterClass
    {
        private int a =70;

        public class InnerClass
        {
            OuterClass instance;

            public InnerClass(OuterClass a_instance)
            {
                instance = a_instance;
            }
            public void AccessVariable(int num)
            {
                this.instance.a = num;
            }
            public void ShowVariable()
            {
                Console.WriteLine("a : {0}", this.instance.a);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            OuterClass outer = new OuterClass();
            OuterClass.InnerClass inner = new OuterClass.InnerClass(outer);

            inner.ShowVariable();
            inner.AccessVariable(60);
            inner.ShowVariable();
        }
    }
}
This post is licensed under CC BY 4.0 by the author.

php-tutorial

컴퓨터개론 14

Comments powered by Disqus.

Trending Tags