C#

C# 2011. 5. 15. 14:30

 

 

접근 제어자 internal, protected internal

    internal        : 어셈블리(하나의 project 기준의 exe 혹은 dll) 기준으로 다른 어셈블리에선 접근 할 수 없도록 한다.

    protected internal     : 다른 어셈블리에서 상속받더라도 public처럼 접근가능하도록 한다.

 

const 와 readonly

    const        : 선언과 함께 초기화해야 하며 변수 값이 사용되는 곳에 박히는 컴파일 타임 상수. (java의 static const 처럼 컴파일시 값이 박힘)

    readonly    : 선언시, 생성자, static 블락 에서 초기화 할 수 있으며 런타임 상수. (const 보단 readonly 사용을 권장)

 

sealed 클래스

    java의 final 처럼 상속하여 사용하지 못하게끔 막아준다.

 

typeof()

    변수의 타입을 알아내는 reflection 함수로 Type 객체를 반환한다.

    java의 instance of 같은 역할을 한다.

 

checked{..}, unchecked{..} 블락

    코드의 overflow를 검사할지 말지를 지정한다.

    포인터 사용등 unsafe한 코드 사용시에 사용하는 것 같다. Ex) checked { //overflow 가능성의 코드 }

 

using(){..} 문

    비싼 인스턴스의 빠른 해제를 위해 사용되며 using 블락이 끝나면 소멸되도록 해준다.

    using(인스턴스) { // 로직 코드.. }

 

out annotation

    함수 호출시 출력용 인자를 넘겨줄때 초기화 하지 않고 넘겨주기 위해 사용하며

호출 및 정의 양쪽에 지정해 준다.

    Ex)    int i;

        func(out i);        // 함수 호출

        void func(out i) { //.. }    // 함수 정의

 

Namespace alias

    namespace에 대한 별칭(alias) 지정. Ex) using alias1 = NameSpace.Code.Class1

 

Attribute

    - DllImport

        C++에서 만들어진 Dll이나 Win32 API를 사용할때 사용된다. Ex) [DllImport("User32.dll")]

    - Obsolete

        특정 메소그나 속성을 사용하지 못하도록 할때 사용한다. Ex) [Obsolete("사용못함")]

    - Conditional

        특정 #define 정의가 된 경우에만 실행하도록 한다. Ex) [Conditional("_MSC_VER")]

    - StructLayout

        VC++의 #pragma pack() 와 동일함.

        Ex)    [StructLayout(LayoutKind.Sequential, Pack = 1)

            public struct STRUCT_SAMPLE {

                // 필드 ..

            }

    - Attribute 정보 획득 방법

        Type.GetType()으로 Type 객체 획득 후 GetFields(), GetMethods()로 foreach()를 돌리면서

GetCustomAttribute()s로 Attribute 객체를 얻는다.

    - 사용자 정의 Attribute

        Attribute를 상속하여 구현

    - 내장 Attribute

        System.ComponentModel, ContextStaticAttribute, Diagnostics, EnterpriseServices, Reflection, Runtime, Security, Web, Xml ..

 

string, StringBuilder

    기본적으로 문자열은 string을 사용하지만 수정이 잦은 경우 메모리 효율을 위해 StringBuilder 사용

    (java의 string, StringBuffer, StringBuilder 처럼..)

 

Collection Class

    ArrayList(value), HashTable(key,value)

 

Thread

    using System.Threading;

    Ex)    Thread th = new Thread();

        th.Name = "thread 1";

        ThreadStart EntryPoint = new ThreadStart(스레드 시작 메소드);

        th.Start(EntryPoint);

 

    동기화는 lock() 사용 : lock(변수) { // 로직 코드.. }

 

Delegate 와 Event

 

 

Assembly

    하나의 프로세스에 여러 응용프로그램이 적재될 수 있는데 이런 응용프로그램 하나에 대한 정의를 한다.

응용 프로그램을 구성하는 기본 단위. (배포, 설치, 버전, 권한 등..)

 

    Shared Assembly    : 다른 응용 프로그램들이 사용할수 있는 Strong Name을 사용하는 어셈블리

                불특정 다수의 클라이언트가 사용하며 GAC(Global Assembly Cache)라는 약속된 디렉토리에 위치

                병렬 설치 지원(이름이 같은 여러개의 버전을 하나의 시스템에 동시 설치)

                **. GAC : 보통 c:\windows\assembly 에 위치함.

    Private Assembly    : 응용 프로그램과 동일/서브 디렉토리에 존재하며 독립적인 전용 어셈블리(권장)

다중 파일 어셈블리    : 여러 개의 파일로 구성되는 어셈블리(콘솔 명령으로 생성가능)

    ildasm.exe        : 어셈블리 내부를 볼 수 있는 프로그램. Ex) C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\ildasm.exe

    Probing (프로빙)    : 클라이언트가 어셈블리 위치를 찾는 방법. Resolve(리졸브)라고도 함.

 

ADO.NET 관련 클래스

    발전 : ODBC -> OLEDB -> ADO -> ADO.NET

 

    DataSet    : DB에 대응. DataTable 집합을 포함. 테이블 관계를 갖을 수 있으며 DB 연결되지 않은 상태에서도 사용 가능.

    DataTable    : 테이블에 대응

    DataRow    : 테이블의 Record에 대응

    DataColumn    : 테이블의 Column에 대응

DataType    : 컬럼 타입

    DataRelation    : DataSet 안의 DataTable 사이의 관계 정보를 갖음.

    Constraint    : 제약사항에 대한 규칙 정의 클래스

    DataColumnMapping    : DB의 열 이름과 DataTable 열이름을 매핑.

    DataTableMapping    : DB 테이블 이름과 DataSet의 DataTable과 매핑.

DataView        : 뷰 테이블에 대응

DataViewManager    : 뷰들을 관리하기 위한 class

 

    SqlCommand, OleDbCommand    : SQL명령문이나 Stored Procedure의 Wrapper

    SqlCommandBuilder, OleDbCommandBuilder    : select 절로부터 insert,updatedelete 등을 생성하기 위해 사용되는 클래스

    SqlConnection, OleDbConnection    : DB 연결로 ADOConnection과 유사

    SqlDataAdapter, OldDbDataAdapter    : CRUD 명령문 저장을 위한 클래스. DataSet에 데이터를 만들고 DB를 update하기 위해 사용

    SqlDataReader, OleDbDataReader    : 연결된 데이터 리더. 전방 탐색으로만 데이터를 읽음

    SqlParameter, OleDbParameter    : Stored Procedure에 대한 매개변수 정의

    SqlTransaction, OleDbTransaction    : DB 트랜잭션 Wrapper

 

    DataGrid 컨트롤    : DB 데이터의 다양한 출력을 위해 제공되는 컨트롤

 

XML 관련 클래스

    XmlReader, XmlTextReader

    XmlWriter, XmlTextWriter

    XmlDocument, DOM

    XPath, XslTransform

    ADO.NET, XmlDataDocument

    XmlSerialization

 

파일 핸들링 클래스

    Stream 종류 : FileStream, BufferedStream, MemoryStream, NetworkStream

    

    FileStream            : 기본적인 File 스트림 개체

        public FileStream (string path, FileMode mode [,FileAccess access, FileShare share, int bufferSize, FileOptions options])

        public FileStream (IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync)

    StreamWriter            : 파일 write 작업을 도와줌

    StreamReader            : 파일 read 작업을 도와줌

    BinaryWriter            : 바이너리 형식의 파일 write

    BinaryRead            : 바이너리 형식의 파일 read

    BinaryFormatter        : 객체의 serialize, deserialize 지원

    

    File                : 파일 관리 (Copy, Delete, Move, Exists, GetAttributes, GetCreationTime)

    FileInfo                : 특정 파일 관리 (CopyTo, MoveTo, Delete, Refresh)

    Directory            : 디렉토리 관리 (CreateDirectory, Delete, Move, Exists, GetFiles, GetDirectories, GetFileSystemEntries)

    DirectoryInfo            : 특정 디렉토리 관리 (Create, Delete, MoveTo, GetDirectories, GetFiles)

    Path                : 경로 문자열 조작을 위한 static 멤버 소유 (GetPathRoot, GetDirectoryName, GetFileName, GetExtention, GetFileNameWithoutExtention, GetFullPath ..)

    FileSystemWatcher 컴포넌트    : 파일 변화 감시

    

System.MarshalByRefObject    : 원격화 될 수 있는 .NET 클래스의 부포 클래스. 응용 프로그램 도메인 사이의 데이터 marshaling 허용.

    FileSystemInfo            : 파일 시스템 객체를 나타내는 기본 클래스

 

 

    ex)    

using System;

        using System.IO;

        using System.Text;

        using System.Runtime.Serialization.Formatters.Binary;

 

        class Test {

            static void Main() {

                //FileStream - write

                using (FileStream fs = new FileStream(@"c:\test.txt", FileMode.Create, FileAccess.Write)) {

                    string contents = "test FileStream write";

                    fs.Write(System.Text.Encoding.ASCII.GetBytes(contents), 0, contents.Length);

                    fs.Close();

                }

 

                //FileStream - read

                using (FileStream fs = new FileStream(@"c:\test.txt", FileMode.Open, FileAccess.Read)) {

                    UTF8Encoding temp = new UTF8Encoding(true);

                    byte[] data = new byte[1024];

                    while (fs.Read(data, 0, data.Length) > 0) {

                        Console.WriteLine(temp.GetString(data).Trim());

                    }

                    fs.Close();

                }

 

                //StreamWriter

                using (StreamWriter sw = new StreamWriter(@"c:\test.txt")) {

                    string contents = "test StreamWriter";

                    sw.WriteLine(contents);

                    sw.Close();

                }

 

                //StreamReader

                using (StreamReader sr = new StreamReader(@"c:\test.txt")) {

                    int len;

                    char[] data = new char[1024];

                    while (true) {

                        len = sr.Read(data, 0, data.Length);

                        Console.WriteLine(new string(data, 0, len));

                        if (len < data.Length) break;

                    }

                    sr.Close();

                }

 

                //BinaryWriter - 바이너리 저장

                using (FileStream fs = new FileStream(@"c:\test.bin", FileMode.Create, FileAccess.Write)) {

                    BinaryWriter bw = new BinaryWriter(fs);

                    bw.Write("binary test");

                    bw.Write(2010);

                    fs.Close();

                }

 

                //BinaryRead - 바이너리 읽기

                using (FileStream fs = new FileStream(@"c:\test.bin", FileMode.Open, FileAccess.Read)) {

                    BinaryReader br = new BinaryReader(fs);

                    string str = br.ReadString();

                    int num = br.ReadInt32();

                    Console.WriteLine("str = {0}, num = {1}", str, num);

                    fs.Close();

                }

 

                //BinaryFormatter - serialize

                using (FileStream fs = new FileStream(@"c:\test.bin", FileMode.Create, FileAccess.Write)) {

                    BinaryFormatter bf = new BinaryFormatter();

                    string str = "serialize/deserialize";

                    bf.Serialize(fs, str);

                    fs.Close();

                }

 

                //BinaryFormatter - deserialize

                using (FileStream fs = new FileStream(@"c:\test.bin", FileMode.Open, FileAccess.Read)) {

                    BinaryFormatter bf = new BinaryFormatter();

                    string str = (string)bf.Deserialize(fs);

                    Console.WriteLine(str);

                    fs.Close();

                }

            }

        }

 

Registry (레지스트리)

    Registry    : 레지스트리 관리

    RegistryKey    : 특정 레지스트리 키

 

 

  

'C#' 카테고리의 다른 글

숫자 범위 추출 및 확장  (0) 2021.11.03
C# LZ4  (0) 2021.10.20
dictionary 에 action 매핑시 instance method 호출 방법  (0) 2021.10.16
[ASP.NET] .net core 2.2 singleton controller  (0) 2019.08.29
[AppMetrics 3.1.0] ASP.NET Core 2.2 모니터링 with InfluxDB, Grafana  (0) 2019.08.06
[asp.net] asp.net core 2.2 iis 게시  (0) 2019.08.03
WPF  (0) 2011.05.08
C# 기초  (0) 2010.12.19