Programming Language/C#

기본 문법

kirhieyes 2013. 1. 11. 23:53

1. 데이터형

  - 타입(실제이름)[디폴트초기값] : 범위

  - sbyte(System.SByte)[0] : -128 ~ 127

  - byte(System.Byte)[0] : 0 ~ 255

  - char(System.Char)['\0'] : 하나의 유니코드 문자. U+0000 ~ U+FFFF

  - short(System.Int16)[0] : -32,768 ~ 32,767

  - ushort(System.UInt16) : 0 ~ 65,535

  - int(System.Int32)[0] : -2,147,483,648 ~ 2,147,483,647

  - uint(System.UInt32) : 0 ~ 4,294,967,295

  - long(System.Int64)[0L] : -9,223,372,036,854,775,808 ~ 반대

  - ulong(System.UInt64) : 0 ~ 18,446,744,073,709,551,615

 

  - float(System.Single)[0.0F] : 7개의 소수자리수

  - double(System.Double)[0.0D] : 15~16개의 소수자리수

  - decimal(System.Decimal)[0.0M] : 28 ~ 29개의 소수자리수

 

  - object(System.Object) : 모든 타입의 최상위 부모 클래스

  - string(System.String) : 문자열

  - bool(System.Boolean)[false] : 참, 거짓

 

2. 배열

  - 1차원 배열 선언 및 초기화

     int[] intArray = new int[5];                          or

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

  - 2차원 배열 선언 및 초기화

     int[][] intDayInMonth = new int[12][];          or

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

  - 배열의 배열 (Jagged Arrays)

    : 배열의 요소를 각각에 맞게 다르게 설정 가능하다.

    : 그냥 배열을 쓰는 것보다 공간 효율이 좋다.

using System;
public class Calendar
{
    public static void Main()
    {
        int[][] intDayInMonth;
        intDayInMonth = new int[12][];
        for (int i = 0; i < 12; i++)
        {
            intDayInMonth[i] = new int[DateTime.DaysInMonth(DateTime.Now.Year, i + 1)];
            for (int j = 0; j < DateTime.DaysInMonth(DateTime.Now.Year, i + 1); j++)
            {
                intDayInMonth[i][j] = 1;
            }
        }
        int sum = 0;
        for (int i = 0; i < 12; i++)
        {
            for (int j = 0; j < DateTime.DaysInMonth(DateTime.Now.Year, i + 1); j++)
            {
                sum += intDayInMonth[i][j];
            }
        }
        Console.WriteLine(DateTime.DaysInMonth(DateTime.Now.Year, 1));
        Console.WriteLine("{0}", sum);
    }
}

 

3. 열거형

using System;

public enum Enumul
{
    온라인입금, 신용카드
}

public class Enumulate
{
    public static void Main(){
        Console.WriteLine("{0}({1})", Enumul.온라인입금,

                                            (int)Enumul.온라인입금);
    }

}

  - 그냥 출력하면 열거형 데이터가 나오고

  - 강제 int casting 하면 인덱스가 나온다.

 

4. 구조체

public struct NameCard
{
    public string name;
    public int age;   
}

public class Struct1
{
    public static void Main()
    {
        NameCard[] testCard = new NameCard[2];
        testCard[0].name = "홍길동";
        testCard[0].age = 21;

        testCard[1].name = "김대현";
        testCard[1].age = 41;
        for (int i = 0; i < testCard.Length; i++)
        {
            Console.WriteLine("이름 : {0}, 나이 : {1}", testCard[i].name, testCard[i].age);
        }       
    }
}

  - 데이터의 복합적인 자료형

 

 

5. 오버플로우 예외처리

  - overflow : 연산결과가 변수 범위를 넘어설 경우 발생하는 오류

 

public class ExceptionTest
{
    public static void Main()
    {
        Console.WriteLine(10 / 0);  //컴파일 오류 발생(빌드자체가 안됨)

        int a = 10;
        int b = 0;
        int c = a / b;
        Console.WriteLine(c);   // 런타임 오류 발생(빌드는 되지만 실행시 에러남)

    }
    public static void OverFlow()   
    {
        byte a = 255;
        checked             // overflow/underflow 가 발생할 경우 오류메세지를 보여줌
        {
            a++;            // overflow 발생
        }
        unchecked             // overflow/underflow 가 발생할 경우 오류메세지를 보여주지않음
        {
            a++;            // overflow 발생
        }
        Console.WriteLine(a);
    }
}

 

6. Try ~ catch

public class TryTest
{
    public static void Main()
    {
        int a = 10;
        int b = 0;

        try     // 예외 감시 시작
        {
            int c = a / b;          // 오류 발생
            Console.WriteLine(c);
        }
        catch (Exception e)   // 예외 발생시 발동
        {
            Console.WriteLine("예외내용 : {0}", e.Message);
        }
        finally // 예외 유무와 상관없이 반드시 실행되는 구문
        {
            Console.WriteLine("프로그램을 정상적으로 종료합니다.");
        }

    }
}

 

7. 네임스페이스

  - 클래스명의 중복 방지

  - 클래스를 계층적으로 관리

  - 회사마다 회사명을 Top 네임스페이스로 구성

  - .Net 프레임워크는 System 이라는 큰 네임스페이스 안에 모두 들어있다.

namespace SampleNamespace
{
    class SampleClass
    {
        public void SampleMethod()
        {
            System.Console.WriteLine(
              "SampleMethod inside SampleNamespace");
        }
    }
}

 

8. 수학관련 클래스

namespace kirhi
{
    public class MathClass
    {
        public static void Main()
        {
            Console.WriteLine("Math.E = {0}", System.Math.E);
            Console.WriteLine("Math.PI = {0}", System.Math.PI);
            Console.WriteLine("-10의 절대값 : {0}", System.Math.Abs(-10));

            int a = 3, b = 5;
            Console.WriteLine("3과 5중 큰 수 : {0}", Math.Max(3, 5));
            Console.WriteLine("2의 10승 : {0}", Math.Pow(2, 10));
            Console.WriteLine("3.154의 반올림 : {0}", Math.Round(3.154, 1));
        }
    }
}

 

9. 날짜/시간관련 구조체

namespace kirhi
{
    public class timeInterval
    {
        public static void Main(string[] args)
        {
            string strDate = "2013-01-19 12:00:00";
            DateTime oldDate = DateTime.Parse(strDate);
            Console.WriteLine(oldDate);

            TimeSpan timeGap = DateTime.Now - oldDate;
            Console.WriteLine(timeGap);
            if (timeGap.TotalHours < 24)
            {
                Console.WriteLine("아직 24시간이 되지않았습니다.");
            }
            else
            {
                Console.WriteLine("24시간이 지났습니다.");
            }
            TimeSpan timeYear = DateTime.Today - DateTime.Parse("2013-1-1");
            Console.WriteLine("올해가 벌써 {0}시간이 지났습니다.", timeYear.TotalHours);
            TimeSpan timeChris = DateTime.Parse("2013-12-25") - DateTime.Today;
            Console.WriteLine("크리스마스가 {0}일 남았습니다.", timeChris.TotalDays);

        }
    }
}

 

10. 난수 생성 클래스

namespace kirhi
{
    public class ranNum
    {
        public static void Main(string[] args)
        {
            Random vari = new Random();
            int[] lotto = {};
            Console.WriteLine(vari.Next());
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine(vari.Next(1, 11));           
            }
           
        }
    }
}

 

11. 스트링 클래스

namespace kirhi
{
    public class stringTest
    {
        public static void Main(string[] args)
        {
            string str = "안녕하세요.";
            string str1 = new String('a', 5);
            Console.WriteLine(str1);
            char[] chaArray = new char[] { '안', '녕', '하', '세', '요', '.' };
            int[] intArray = new int[] { 1, 2, 3, 4, 5 };
            string str2 = new String(chaArray, 2, 3);           
            Console.WriteLine(str2);
        }
    }
}

 

12. 클래스

1) 객체 : 어떤 데이터를 지니며 어떤 동작을 수행할 수 있는 하나의 단위/모듈

  - 자동차, 사람, 컴퓨터,....

2) 속성 : 객체가 지니는 성질, 색상, 크기, 모양등을 나타내는 단위

  - 빨간색, 바퀴4개, 문짝2개,...

3) 메서드 : 객체가 수행할 수 있는 동작

  - 이동, 전투, 회전,...

4) 이벤트 : 객체가 지니는 메서드의 수행 결과

  - 교통사고

using System;

namespace kirhi
{
    public class Car
    {
        // 필드
        private string _Engine;
        private string _Color;


        // 생성자
        public Car()
        {
            _Engine = "2000CC";
            _Color = "Red";
        }
       

        // 속성
        public string Color
        {
            get { return _Color; }
            set { _Color = value; }
        }

 

        // 메서드
        public void Run()
        {
            Console.WriteLine("{0}, {1} 자동차가 달립니다.", _Engine, _Color);
        }
        ~Car()
        {
            Console.WriteLine("자동차를 폐차합니다.");
        }
    }
    public class CarTest
    {
        public static void Main()
        {
            Car car = new Car();

            car.Run();
        }
    }
}

 

13. 클래스의 성격

public class IntegerClass
{
    public static readonly int MinValue = int.MinValue;
    public static readonly int MaxValue = int.MaxValue;
    public int value;

    public IntegerClass(int value)
    {
        this.value = value;
    }
    // 변환 연산자
    public static implicit operator IntegerClass(int value)
    {
        return new IntegerClass(value);
    }
    // 단항 연산자 오버로드
    public static IntegerClass operator ++(IntegerClass value)
    {
        return ++value.value;
    }
    // 이항 연산자 오버로드
    public static IntegerClass operator +(IntegerClass value1, IntegerClass value2)
    {
        return value1.value + value2.value;
    }
    // Object 클래스의 ToString() 메서드의 오버라이드
    public override string ToString()
    {
        return value.ToString();    // value 필드의 내용을 문자열로 반환
    }

    public static void Main()
    {
        //IntegerClass intVal = new IntegerClass(1);
        // 변환 연산
        IntegerClass intVal = 1;
        // 단항 연산자 오버로드
        ++intVal;
        Console.WriteLine("정수값 : {0}", intVal.value);
        Console.WriteLine("최대값: {0}", IntegerClass.MaxValue);
        Console.WriteLine("최대값: {0}", IntegerClass.MinValue);

        // 이항 연산자 오버로드
        IntegerClass intVal1 = 10;
        IntegerClass intVal2 = 20;

        IntegerClass sum = intVal1 + intVal2;

        Console.WriteLine("두 값의 합 : {0}", sum.value);

        // 메서드 오버라이드
        Console.WriteLine("두 값의 합 : {0}", sum);
    }
}

 

14. 코드 스니펫 & 인텔리센스

- C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC#\Snippets\1042\Visual C# 폴더에 들어가 스니펫파일을 하나 만들어서 아래와 같이 작성한다. ( 볼드 부분만 수정하면 된다. )

 

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
 <CodeSnippet Format="1.0.0">
  <Header>
   <Title>dim</Title>
   <Shortcut>dim</Shortcut>
   <Description>Object 생성</Description>
   <Author>Kirhieyes</Author>
   <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
    <SnippetType>SurroundsWith</SnippetType>
   </SnippetTypes>
  </Header>
  <Snippet>
   <Declarations>
    <Literal>
     <ID>object</ID>
     <ToolTip>Class type</ToolTip>
     <Default>Object</Default>
    </Literal>
        <Literal>
          <ID>name</ID>
          <ToolTip>Class name</ToolTip>
          <Default>newName</Default>
        </Literal>
   </Declarations>
   <Code Language="csharp"><![CDATA[$object$ $name$ = new $object$(); 
         $selected$ $end$
         ]]>
   </Code>
  </Snippet>
 </CodeSnippet>
</CodeSnippets>

 

- 메서드이름에서 우클릭으로 using 구성 메뉴를 사용하면 선언되지 않은 모듈을 using 으로 선언 추가가 가능하다.