.NET 리모팅

.NET 리모팅(.NET Remoting)은 서로 다른 프로세스 영역, 혹은 서로 다른 호스타에 존재하는 모듈간에 정보 교환을 손쉽게 할 수 있는 방법 입니다. 

.NET에서 제공하는 리모팅은 DCOM이나 CORBA의 한계를 극복하고자 나온 것 이라고 할 수 있습니다. 웹 서비스 역시 내부적으로는 리모팅을 사용하고 있으며 사실상 리모팅을 손쉽게 사용할 수 있는 일종의 껍데기에 불과합니다.


.NET 리모팅의 동작 원리

개발자가 기본적으로 작성해야 하는 부분은 서버 객체, 호스팅 어플리케이션, 그리고 클라이언트 어플리케이션 입니다. 수행하고자 하는 서버 작업은 서버 객체가 처리하며, 말 그대로 객체이기 때문에 클라이언트로의 요청을 받아 객체의 생성과 소멸을 처리해주는 대리인이 필요합니다. 이 대리인을 어플리케이션에게 특정 객체를 사용하겠다는 요청을 하면 호스팅 어플리케이션은 먼저 그 객체를 자기가 관리하고 있는지 체크하고 객체를 생성하여 클라이언트와 연결시켜 줍니다. 


원격객체(Remote Object)

리모팅이 나오게 된 가장 큰 목적 중의 하나는 원격 객체의 메서드를 호출하고 결과값을 전달받아 복잡한 과정을 개발자에게 숨기고 단순한 인터페이스를 제공하기 위함입니다. 여기서 원격 객체라 함은 클라이언트와 다른 어플리케이션 도메인에 객체가 존재한다는 의미 입니다.

클라이언트에 객체를 전달하는 방식에는 객체에 대한 참조값만 넘기는 방법과 객체 자체를 넘기는 방법이 있는데, 객체와 클라이언트가 같은 어플리케이션 도메인에 있느냐 아니냐에 따라 어떤 방법을 쓸 것인지가 결정됩니다. 객체와 클라이언트가 같은 어플리 케이션 도메인에 있는 경우에는 객체에 대한 참조값만을 넘김으로써 클라이언트가 그 객체를 사용할 수 있으나, 서로 다른 어플리케이션 도메인에 존재하는 경우에는 반드시 객체 자체를 클라이언트로 전달해야 합니다.

이 때 .NET 프레임워크는 객체를 시리얼라이즈(Serialize)하여 클라이언트에게 전달하고 클라이언트는 그 데이터를 사용하여 객체를 생성합니다. 로컬객체를 시리얼라이즈하기 위해서는 [serializable]이라는 성송을 부여하는데, 이 속성이 지정되지 않았거나 인터페이스가 구현되지 않은 객체는 시리얼라이즈가 되지 않기 때문에 원격 객체로 사용할 수 없습니다.

.NET에서는 객체를 MarshalByRefObject로부터 상속시킴으로써 원격 객체를 생성할 수 있는데, 이 때클라이언트는 이 객체에 대한 프록시를 사용하게됩니다. 프록시와 원격 객체가 같은 어플리케이션 도메인에 있으면 프록시는 원격 객체의 메서드를 직접 호출하고 결과를 받아 클라이언트에게 돌려줍니다. 만약 프록시와 원격 객체가 별개의 어플리케이션 도메인에 존재한다면 프록시는 클라이언트의 요청을 메시지로 변환하여 원격 객체에게 전송합니다. 원격 객체쪽에서는 메시지를 자신이 이해할 수 있는 방식으로 변환한 후 클라이언트의 요청을 수행하고 결과값을 다시 메시지로 바꾸어 프록시에게 보냅니다. 프록시는 이 메시지로 부터 결과값을 얻어내어 클라이언트에게 넘겨줍니다.


프록시 객체

클라이언트가 원격 객체를 사용하고자 할 때 프록시가 생성됩니다. 프록시는 TransparentProxy와 RealProxy로 나뉘는데 클라이언트가 사용하는 것은 TransparentProxy이다. 원격 객체와 TransparentProxy가 같은 어플리케이션 도메인에 있으면 TransparentProxy는 원격 객체에 직접 접근하여 메서드를 호출한다. 만약 원격 객체와 TransparentProxy가 서로 다른 어플리케이션 도메인에 있으면 TransparentProxy는 클라이언트가 호출한 메서드의 매개변수를 메시지로 변환하여 RealProxy에게 전송한다. RealProxy는 원격 객체에 접근하여 매개변수가 담긴 메시지를 넘겨주며 메서드의 결과값은 RealProxy와 TransparentProxy를 거쳐 클라이언트가 받게 된다. 

클라이언트가 TransparentProxy에 대해 메서드를 호출하면 그정보는 메시지로 변환되여 RealProxy로 전달되고, RealProxy는 메시지를 포맷터 싱크에 넘긴다.(formatter sink) 포맷터 싱크는 하나 이상의 포매터가 파이프처럼 연결된 형태이며, 메시지를 바이너리 스트림 혹은 XML 스트림으로 변환해서 트랜스포트 싱크(transport sink)에 전닳나다. 트랜스포트 싱크 역시 하나 이상의 트랜스포트 포맷터로 구성되어 있는 형태이며 서버측의 트랜스포트 싱크와 연결하여 데이터를 전송하고, 서버측의 트랜스포트 싱크는 시리얼라이즈되어 전달된 데이터를 포맷터 싱크로 전달한다. 포맷터 싱크는 데이터 스트림을 원격 객체가 사용할 수 있는 데이터로 복원하여 원격 객체에게 전달한다. 결과값 전송은 이와 반대 순서로 진행된다.


활성화와 프록시 객체의 개요

· 원객 객체 활성화 방법

   ° 서버 활성화 객체(SAO : Server Activated Object)

      · SingleCall 방식 - 함수 호출 요청이 있을 때마다 객체 생성

      · Singleton 방식 - 클라이언트 함수 호출 요청이 있을 때 하나의 객체를 생성한 후 하나의 객체를 공유

   ° 클라이언트 활성화 객체(CAO : Client Activated Object)

· 서버 활성화와 클러이언트 활성화

   ° 서버에 의해서 원격 객체가 자동으로 만들어지면 서버 활성화 기법이라고 한다.

   ° 클라이언트에서 프록시 객체를 만들 때 원격 객체가 만들어지면 클라이언트 호라성화 기법이라고 한다.

·클라이언트의 프록시

   ° 클라이언트에서는 원격 객체를 참조하기 위한 가상의 객체를 만들게 되는데 이 객체를 프록시 객체라고 한다.

   ° 이 프록시 객체를 이용해서 클라이언트는 원격 객체를 핸들링 할 수 있다.

· 프록시 객체를 생성하는 방법

   ° new를 사용하는 방법 : 서버 활성화, 클라이언트 활성화에서 사용

   ° Activator.GetObject() 함수를 사용하는 방법 : 서버 활성화에서 사용

   ° Activator.CreateInstance() 함수를 사용하는 방법 : 클라이언트 활성화에 사용

'Programing > C#&.Net' 카테고리의 다른 글

speech To Text  (0) 2016.11.30
회원관리 연습  (0) 2016.11.30
직렬화(Serializable) 예제  (0) 2016.11.30
명시적 어셈블리 로딩  (0) 2016.11.30
인덱서(Indexer) 예제  (0) 2016.11.30


AboutSerialize.zip



직렬화(Serializable)


개체의 상태 데이터를 일정한 위치(메모리,물리적 파일 등) 에 선형적인방법으로 지속시키는 것을 말한다.

BinaryFormatter를 이용한 직렬화와 SoapFormatter를 사용한 직렬화로 2가지가있다.


바이너리 직렬화(BinaryFormatter 사용)


바이너리 직렬화는, 타입이 원래 객체의 타입과 똑같도록 보존해 줍니다. 객체의 상태를 다른 응용프로그램 호출 사이에

보존하고자 할 때 유용합니다. Binary라는 용어가 저장매체에 저장되어 있는 객체와 동일한 복사본을 생성하는데 필요한

필수적인 정보라는 뜻을 가지고 있습니다. 


SOAP 직렬화


SOAP 프로토콜은 서로 다른 아키텍쳐를 가지는 어플리케이션 간의 통신에 이상적입니다. .NET에서 SOAP Serialization을 이용하면

어플리케이션이 System.Runtime.Serialization.Formatter.Soap을 참조해야 합니다. SOAP 직렬화의 기본적인 장점은 

이식성 입니다. SoapFormatter는 객체를 직렬화해서 SOAP 메시지로 바꾸거나, SOAP 메시지로를 파싱해서 직렬화된 객체를 추출해 냅니다.



바이너리 형식으로 저장된 정보 






직열화 예제 코드


Main Class

 using System.Runtime.Serialization.Formatters.Binary; 


namespace AboutSerialize 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            School school = new School(); 
            Console.WriteLine("Serialize 이전"); 
            Stu s1 = new Stu(1"a1"); 
            school.AddStu(s1); 
            Stu s2 = new Stu(2"a2"); 
            school.AddStu(s2); 
            Stu s3 = new Stu(3"a3"); 
            school.AddStu(s3); 
            Stu s4 = new Stu(4"a4"); 
            school.AddStu(s4); 
            Stu s5 = new Stu(5"a5"); 
            school.AddStu(s5); 
            school.AllView(); 

            FileStream fs = new FileStream(@"cozy.txt", FileMode.Create); 
            BinaryFormatter bf = new BinaryFormatter(); 

            bf.Serialize(fs, school); 
            fs.Close(); 

            Console.WriteLine("DeSerialize 한 개체"); 
            fs = new FileStream(@"cozy.txt", FileMode.Open); 
            School school2 = bf.Deserialize(fs) as School; 
            school2.AllView(); 
            fs.Close(); 
        } 
    } 
}


Stu Class

 namespace AboutSerialize 


    [Serializable] 
    class Stu 
    { 
        int num; 
        string name; 
        public Stu(int _num, string _name) 
        { 
            num = _num; 
            name = _name; 
        } 
        public override string ToString() 
        { 
            return "이름은 : " + name + " 번호 : " + num; 
        } 
    } 
}


School Class

 namespace AboutSerialize 


    [Serializable] 
    class School 
    { 
        List<Stu> list = new List<Stu>(); 
        public void AllView() 
        { 
            foreach (Stu s in list) 
            { 
                Console.WriteLine(s.ToString()) ; 
            } 
        } 
        public void AddStu(Stu s) 
        { 
            list.Add(s); 
        } 
    } 
}


'Programing > C#&.Net' 카테고리의 다른 글

회원관리 연습  (0) 2016.11.30
.NET 리모팅  (0) 2016.11.30
명시적 어셈블리 로딩  (0) 2016.11.30
인덱서(Indexer) 예제  (0) 2016.11.30
Delegate(대리자) 프로그램  (0) 2016.11.30


Stu클래스를 클래스 라이브러리로 생성하고 해당 테스트 클래스 디버그 파일이 있는 곳에 복사해 두었다.    


using System; 

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Student 

    public class Stu 
    { 
        int num; 
        string name; 
        public Stu(int _num, string _name) 
        { 
            num = _num; 
            name = _name; 
        } 
        public void Study() 
        { 
            Console.WriteLine("{0}학생 공부중입니다.", name); 
        } 
        public override string ToString() 
        { 
            return "이름 : " + name + "  번호 :" + num; 
        } 
    } 



테스트 클래스이다.

dll을 직접 등록하지 않고 명시적으로 등록하여 Stu에 있는 Study 함수를 호출하는 예제이다.

using System; 

using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Reflection; 

namespace 명시적어셈블리로딩 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            Assembly asm = Assembly.Load("Student"); 
            Type type = asm.GetType("Student.Stu"); 
            Object o = Activator.CreateInstance(type,1,"홍길동"); 
            MethodInfo mi = type.GetMethod("Study"); 
            mi.Invoke(o, null); 
        } 
    } 
}


'Programing > C#&.Net' 카테고리의 다른 글

.NET 리모팅  (0) 2016.11.30
직렬화(Serializable) 예제  (0) 2016.11.30
인덱서(Indexer) 예제  (0) 2016.11.30
Delegate(대리자) 프로그램  (0) 2016.11.30
리플렉션 활용  (0) 2016.11.30


Indexer.zip



인덱서 사용예제


해당 클래스의 인덱서를 정의하여 사용하였다 string 값을 입력받아 Stu 클래스의 num 값을 반환한다.


Main class

  1 namespace Indexer

  2 {
  3     class Program
  4     {
  5         static void Main(string[] args)
  6         {
  7             Manager m = new Manager();
  8             Stu s = new Stu(1, "홍길동");
  9             Stu s1 = new Stu(2, "후후훗");
 10             Stu s2 = new Stu(3, "히히힛");
 11             m.AddStu(s);
 12             m.AddStu(s1);
 13             m.AddStu(s2);
 14             int num,num1,num2;
 15             num = m["홍길동"];
 16             num1 = m["후후훗"];
 17             num2 = m["히히힛"];
 18             Console.WriteLine("{0},{1},{2}",num, num1, num2);
 19         }
 20     }
 21 }


Stu class

  1 using System;

  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 namespace Indexer
  7 {
  8     class Stu
  9     {
 10         int num;
 11         string name;
 12         List<Stu> arr = new List<Stu>();
 13         public Stu(int _num, string _name)
 14         {
 15             num = _num;
 16             name = _name;
 17         }
 18         public int Num
 19         {
 20             get
 21             {
 22                 return num;
 23             }
 24         }
 25         public string Name
 26         {
 27             get
 28             {
 29                 return name;
 30             }
 31         }
 32     }
 33 }
 34 


Manager class

  1 using System;

  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 
  6 namespace Indexer
  7 {
  8     class Manager
  9     {
 10         List<Stu> arr = new List<Stu>();
 11 
 12         public void AddStu(Stu a)
 13         {
 14             arr.Add(a);
 15         }
 16         public int this[string n] // 반환형 데이터 타입int 입력을 string n 
 17         {
 18             get
 19             {
 20                 foreach (Stu stu in arr) // 받아온 값을 비교하여 리턴해준다.
 21                 {
 22                     if (stu.Name == n)
 23                     {
 24                         return stu.Num;
 25                     }                    
 26                 }
 27                 return 0;
 28             }
 29         }
 30     }
 31 }
 32 


'Programing > C#&.Net' 카테고리의 다른 글

직렬화(Serializable) 예제  (0) 2016.11.30
명시적 어셈블리 로딩  (0) 2016.11.30
Delegate(대리자) 프로그램  (0) 2016.11.30
리플렉션 활용  (0) 2016.11.30
리플렉션(reflection)  (0) 2016.11.30


AboutDelegate.zip



시나리오.


학교에 있는 학생을 도서관으로 이동하여 비동기 적으로 공부를 수행하고 끝난 후 다시 학교로 복귀하도록 구성하였다.


Main class

  1 namespace AboutDelegate

  2 {
  3     class Program
  4     {
  5         static void Main(string[] args)
  6         {
  7             School sc = new School();
  8             sc.GoLibrary();
  9             Console.WriteLine("호호호~~");
 10             Thread.Sleep(2500);
 11             Console.WriteLine("호호호~~");
 12             Thread.Sleep(2500);
 13             Console.WriteLine("호호호~~");
 14             Thread.Sleep(2500);
 15             Console.WriteLine("호호호~~");
 16             Thread.Sleep(2500);
 17             Console.ReadLine();
 18         }
 19     }
 20 }



Stu class

  1 using System;

  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading;
  6 
  7 namespace AboutDelegate
  8 {
  9     public class Stu
 10     {
 11         int num;
 12         string name;
 13         public Stu(int _num, string _name)
 14         {
 15             num = _num;
 16             name = _name;
 17         }
 18         public string Name
 19         {
 20             get
 21             {
 22                 return name;
 23             }
 24         }
 25         public int Num
 26         {
 27             get
 28             {
 29                 return num;
 30             }
 31         }
 32 
 33         public void Study(int cnt)
 34         {
 35             for (int i = 0; i < cnt; i++)
 36             {
 37                 Console.WriteLine("{0} 학생 {1} 시간째 공부중", Name, i+1);
 38                 Thread.Sleep(2500);
 39             }
 40         }
 41     }
 42 }
 43 


School class


  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Runtime.Remoting.Messaging;
  6 
  7 namespace AboutDelegate
  8 {    
  9     class School
 10     {
 11        
 12         Library lb=null;
 13         List<Stu> list = new List<Stu>();
 14         public School()
 15         {
 16             lb = new Library();
 17             Stu s = new Stu(1, "조스타");
 18             lb.AddStu(s);
 19             Stu s1 = new Stu(2, "좆스타");
 20             lb.AddStu(s1);
 21             Stu s2 = new Stu(3, "좆밥타");
 22             lb.AddStu(s2);
 23             Stu s3 = new Stu(4, "조스타킹");
 24             lb.AddStu(s3);
 25             Stu s4 = new Stu(5, "조조전");
 26             lb.AddStu(s4); 
 27             lb.SchoolCallEventHandler += new CallBackTest(EndStudy);
             //Library 에있는 SchoolCallEventHandler에 EndSTudy 함수를 등록한다(함수 포인터와 비슷)
 28         }
 29 
 30         public void GoLibrary()
 31         {
 32             lb.StartStudy();
 33         }
 34         public void EndStudy(Stu stu)
 35         {
 36             Console.WriteLine("{0} 학생 공부 완료", stu.Name);
 37             list.Add(stu);
 38             Console.WriteLine("{0} 학생 학교 복귀", stu.Name);
               // 학생 복귀
 39         }
 40     }
 41 }
 42 
 


Libray class

  1 using System;

  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Runtime.Remoting.Messaging;
  6 
  7 namespace AboutDelegate
  8 {
  9     public delegate void CallBackTest(Stu stu); 
 10     class Library
 11     {
 12         delegate void OnStudy(Stu s,int cnt);
 13         public event CallBackTest SchoolCallEventHandler; CallBackTest 이벤트 선언하여 School에서 사용
 14 
 15         List<Stu> list = new List<Stu>();
 16 
 17         public Library()
 18         {
 19         }
 20         public void AddStu(Stu s)
 21         {
 22             list.Add(s);
 23         }
 24         public void StartStudy()
 25         {            
 26             Random rand = new Random();
 27             OnStudy os;
 28             if (SchoolCallEventHandler != null)
 29             {
 30                 foreach (Stu stu in list)
 31                 {
 32                     os = new OnStudy(StudyOn); //학생마다 비동기적으로 동작해야 하므로 매번생성
 33                  os.BeginInvoke(stu, 3, EndOnStudy, stu);
                            //입력매개 변수 타입과 갯수만큼 앞에 넣어주고 다끝나고 동작할 함수 EndOnStudy를 등록한다.
 34                 }
 35             }
 36         }
 37 
 38         public void StudyOn(Stu s,int cnt)
 39         {
 40             //Console.WriteLine("{0} 번 학생 {1} 시간째 공부중", s.Name, cnt);
 41             s.Study(cnt);
 42         }
 43 
 44         public void EndOnStudy(IAsyncResult iar)
 45         {
 46             AsyncResult ar = iar as AsyncResult;
 47             Stu st = ar.AsyncState as Stu;
 48 
 49             OnStudy os = ar.AsyncDelegate as OnStudy;
 50             os.EndInvoke(iar);
 51             if (SchoolCallEventHandler != null)
 52             {
 53                 SchoolCallEventHandler(st); // 전에 등록한 이번트를 호출하여 학생을 되돌려주고 지워준다
 54              list.Remove(st);
 55             }
 56         }
 57     }
 58 }
 59 


'Programing > C#&.Net' 카테고리의 다른 글

명시적 어셈블리 로딩  (0) 2016.11.30
인덱서(Indexer) 예제  (0) 2016.11.30
리플렉션 활용  (0) 2016.11.30
리플렉션(reflection)  (0) 2016.11.30
어셈블리,메타데이터  (0) 2016.11.30

리플렉션활용


기존에 만들엇던 dll을 직접 등록하지 않고 런타임시 dll을 로딩해 사용하도록 하였다.


  class Program

    {
        static void Main(string[] args)
        {
            Assembly asm = Assembly.Load("SumBit");
            Type type = asm.GetType("SumBitS.SumBit");
            Object obj = Activator.CreateInstance(type);
            MethodInfo mi = type.GetMethod("Run");
            mi.Invoke(obj,null);
        }
    }


'Programing > C#&.Net' 카테고리의 다른 글

인덱서(Indexer) 예제  (0) 2016.11.30
Delegate(대리자) 프로그램  (0) 2016.11.30
리플렉션(reflection)  (0) 2016.11.30
어셈블리,메타데이터  (0) 2016.11.30
형식 메타데이터  (0) 2016.11.30

리플렉션


.NET 환경에서 리플렉션은 런타임에 형식에 대한 정보를 얻는 과정이다. 리플렉션 서비스를 이용하면, 런타임에 어셈블리를 로드할 수 있고, ildasm 메타데이터 창에서 볼 수 있었던 것과 같은 종류의 정보를 찾아낼 수 있다. 

리플렉션을 이용해 해당 어셈블리에 포함되어 있는 모든 형식들의 목록과 각 형식에 정의된 메소드,필드,속성 그리고 이벤트 등을 얻어낼 수 있다. 또한 해당 클래스가 지원하는 인터페이스나,메소드의 매개변수뿐만 아니라 기타 관련 내용들(기본클래스의 상세내용, 네임 스페이스 정보, 매니페스트 데이터 등)도 동적으로 찾아낼 수 있다.

'Programing > C#&.Net' 카테고리의 다른 글

Delegate(대리자) 프로그램  (0) 2016.11.30
리플렉션 활용  (0) 2016.11.30
어셈블리,메타데이터  (0) 2016.11.30
형식 메타데이터  (0) 2016.11.30
c# 프로그램 연습  (0) 2016.11.30

정의하는 어셈블리 문서화



어셈블리의 메타 데이터는 내부 형식들 뿐만 아니라 이 형식들에 의해서 참조되는 외부 형식들도 설명한다. 

System.Object형식에 대한 대한 TypeRef 블록을 볼 수 있다.





ildasm 메타데이터 창을 이용하면 Assembly 토큰을 이용해서 어셈블리 자신을 설명하는데 .NET 메타데이터를 볼 수도 있다. 다음의 목록에서 볼 수 있듯이 Assembly 테이블에 기록된 정보는 MAINIFEST 아이콘을 통해 볼수 있는 정보와 동일하다.





.NET 메타데이터는 TypeDef와 TypeRef블록과 Assembly 토큰 이외에도, AssemblyRef#n 토큰을 이용해서 각외부 어셈블리를 문서화 한다. MyFirstAssembly.dll 을 통해 사용하고 있는 것에 대한 AssemblyRef를 볼 수 있다.




.NET 메타데이테의 코드 베이스에 있는 모든 문자열 리터럴이 User Strings 토큰 아래에 문서화 된다. 




.NET 메타데이터가 매우 설명적이고 해당 코드 베이스에 있는 모든 내부에 정의된 형식을 나열하고 있다는 것이다. 

이 정보를 어떻게 활용할 수 있을지와 애ㅗ 신경써야하는 부분을 고려하기 위해선 .NET 리플렉션 서비스에 대해 알아보야 한다.


'Programing > C#&.Net' 카테고리의 다른 글

리플렉션 활용  (0) 2016.11.30
리플렉션(reflection)  (0) 2016.11.30
형식 메타데이터  (0) 2016.11.30
c# 프로그램 연습  (0) 2016.11.30
Delegate(대리자)  (0) 2016.11.30

메타데이터

메타데이터를 이용해서 형식을 완전하게 설명할 수 있다는 것이 .NET 런타임의 핵심 요소이다. 직렬화(serialization),원격(remotion),XML 웹 서비스와 같은 .NET기술은 모두 런타임에 형식들의 포멧을 알아낼 수 있기 때문에 가능한 것이다. 또한 교차 언어 상호운용성,컴파일러 지원, IDE의 인텔리센스 기능도 모두 형식에 대한 구체적인 설명이 있기 때문에 가능한 것이다. .NET형식은 클래스,인터페이스,구조체,열거형,델리게이트 중 하나이다. .NET 메타데이터는 이 형식들의 내부 구성을 설명하는데 이용되는 매개체이다. 


메타데이터는 그 중요성에도 불구하고 .NET Framework에만 있는 새로운 개념은 아니다. 예를 들어,COM에서 IDL은 해당 COM  서버 안에 있는 내부 COM 형식을 설명하는 데 이용된다. COM과 같이 .NET코드 라이브러리도 형식 메타데이터를 지원한다. .NET형식 메타데이터는 COM IDL과 동일한 문법을 갖지는 않는다. 형식 메타데이터는 내부적으로 더 도표화된(인덱스가 있는)포멧 문서화 된다. 


ildasm.exe 에 Ctrl+M 을 누루면 형식 메타데이터를 확인할 수 있다.



'Programing > C#&.Net' 카테고리의 다른 글

리플렉션(reflection)  (0) 2016.11.30
어셈블리,메타데이터  (0) 2016.11.30
c# 프로그램 연습  (0) 2016.11.30
Delegate(대리자)  (0) 2016.11.30
dll만들기 명령 프롬프트 사용  (0) 2016.11.30







-as , is 연산자

  1 private int checktype(Man mi)

  2         {
  3             if (mi is Stu && !(mi is StuTea)) return 1;            
  4             if (mi is StuTea) return 2;
  5             if (mi is Tea && !(mi is TeaStu)) return 3;
  6             if (mi is TeaStu) return 4;
  7 
  8             return -1;
  9         }



1 foreach (Stu st in lb)

  2             {
  3                 int num;
  4                 if ((num = lb.Compare(st, name)) == 1)
  5                 {
  6                     Stu stu = st;
  7                     return  stu as Man;
  8                 }
  9             }



-명시적, 묵시적 인터페이스 구현

  //명시적 인터페이스!

        void ITeach.Work()
        {
            Console.WriteLine("학생 선생입니다~ 공부하고 일하고 바빠~ 바쁨 IQ-2");
            int Iq = this.IQS;
            this.SettingIq(ref Iq, -2);
        }
        //묵시적 인터페이스!
        public void Teach()
        {
            Console.WriteLine("학생 선생입니다~ 가르칩니다~ IQ+2");            
        }

-static 클래스 구현

  public static class ShowWindow

    {      
        // 읽기전용 static 읽기전용
        static readonly ArrayList arr;
        static ShowWindow()
        {  
            arr = new ArrayList();
            SetShowwindow();
        }

        private static void SetShowwindow()
        {
           arr.Add(new Stu("조대준",42));            
           arr.Add(new Stu("대마왕", 142));
            
            arr.Add(new StuTea("조스타", 124));
            arr.Add(new StuTea("킹스타", 102));
           
            arr.Add(new Tea("최강사", 50));            
            arr.Add( new Tea("진짜강사", 84));
            
            arr.Add( new TeaStu("진중왕",45));            
            arr.Add(new TeaStu("왕중진", 55));          
            
        }

        public static string StaticToString()
        {
            bool type = false;
            foreach (object o in arr)
            {
                if (o is Stu && !(o is StuTea))
                {
                    if (!type)
                    {
                        Console.WriteLine("========= 학생 =========");
                    }
                    Console.WriteLine(o.ToString());
                    type = true;
                }
                if (o is StuTea)
                {
                    if (type)
                    {
                        Console.WriteLine("=========학생 선생 =========");
                    }
                    Console.WriteLine(o.ToString());
                    type = false;
                }

                if (o is Tea && !(o is TeaStu))
                {
                    if (!type)
                    {
                        Console.WriteLine("=========  선생 =========");
                    }
                    Console.WriteLine(o.ToString());
                    type = true;
                }

                if (o is TeaStu)
                {
                    if (type)
                    {
                        Console.WriteLine("========= 선생 학생=========");
                    }
                    Console.WriteLine(o.ToString());
                    type = false;
                }
            }
            return null;
        }

        public static Man CompareName(string _name)
        {            
            foreach (Man o in arr)
            {
                if (o.Name == _name)
                {
                    if (o is Stu && !(o is StuTea))
                    {
                        Stu stu = o as Stu;
                        return stu.Clone() as Man;   
                    }
                    if (o is StuTea)
                    {
                        StuTea stutea = o as StuTea;
                        return (StuTea)stutea.Clone() as Man;                        
                    }
                    if (o is Tea && !(o is TeaStu))
                    {
                        Tea tea = o as Tea;
                        return tea.Clone() as Man;
                    }
                    if(o is TeaStu)
                    {
                        TeaStu tea = o as TeaStu;
                        return (TeaStu)tea.Clone() as Man;
                    }
                    return null;
                }                
            }
            return null;
        }
    }

-static 생성자 구현

  //static 생성자!!

        static LecturRoom()
        {
            singleton = new LecturRoom();
        }
        private LecturRoom()
        {
            Console.WriteLine("강의실 생성");
            Console.ReadLine();
        }    

-abstract 클래스 구현

 //abstract 클래스!!!

    public abstract class Man: IComparable
    {
        string name;             

        readonly int hp;
        const int min_Hp = 0;
        const int max_Hp = 100;

        public Man(string _name)
        {
            name = _name;
            hp = max_Hp;
        }
        //비대칭 속성!!
        public string Name
        {
            get
            {
                return name;
            }
            private set
            {
                if (Avail(value))
                {
                    name = value;
                }
            }
        }

        private bool Avail(string value)
        {
            return (value != null);
        }


        public int CompareTo(object obj)
        {
            Man man = obj as Man;
            if(man !=null)
            {
                return this.Name.CompareTo(man.Name);
            }
            else
            {
                throw new Exception("안되요...");
            }
        }
        public override string ToString()
        {
            return "체력 : " + hp+"\n";
        }  

    }

    class StuHelper :IComparer<Man>
    {
        #region IComparer(Man) 멤버

        public int Compare(Man x, Man y)
        {
            return x.Name.CompareTo(y.Name);
        }

        #endregion
    }

-sealed 클래스 구현

 // sealed 클래스!!

    public sealed class TeaStu : Tea  ,IStudy,ICloneable
    {
        public TeaStu(string _name, int _charisma)
            : base(_name, _charisma)
        {
        }
        public TeaStu(string _name)
            : base(_name)
        {
        }
        public override string ToString()
        {
            return base.ToString();
        }
        public void Study()
        {
            Console.WriteLine(" 강사지만 열심히 공부한다~~~");
        }
        public override void Heal()
        {
            Console.WriteLine("선생이 배우고 가르치고 힘들다 쉬어야지~~");            
        }

        #region ICloneable 멤버

        public object Clone()
        {
            Console.WriteLine("이름을 입력하세요~");
            string _name = Console.ReadLine();
            return new TeaStu(_name, this.Charisma);
        }

        #endregion
    }

-ToString 재정의 구현

  //ToString 재정의!

        public override string ToString()
        {
            return "이름 : " + this.Name + " 카리스마 : " + charisma + "\n" + base.ToString();
        }

-읽기전용, static 읽기전용 구현

  public static class ShowWindow

    {      
        // 읽기전용 static 읽기전용
        static readonly ArrayList arr;
        static ShowWindow()
        {  
            arr = new ArrayList();
            SetShowwindow();
        }
    }

-const 멤버 구현 (Man 속성)

  const int min_Hp = 0;

const int max_Hp = 100;


-비대칭 속성 구현 (Man 속성)

  //비대칭 속성!!

        public string Name
        {
            get
            {
                return name;
            }
            private set
            {
                if (Avail(value))
                {
                    name = value;
                }
            }
        }

-base 키워드 구현
-IComparer,IComparable 구현 (Stu 클래스 내 구현, Helper클래스 사용)

  public int CompareTo(object obj)

        {
            Man man = obj as Man;
            if(man !=null)
            {
                return this.Name.CompareTo(man.Name);
            }
            else
            {
                throw new Exception("안되요...");
            }
        }
       

    }

    class StuHelper :IComparer<Man>
    {
        #region IComparer(Man) 멤버

        public int Compare(Man x, Man y)
        {
            return x.Name.CompareTo(y.Name);
        }

        #endregion
    }

-IEnumerable,IEnumerator 구현(LectureRoom)

  #region IEnumerator 멤버

        object IEnumerator.Current
        {
            get
            {
                if (iteach != null)
                {
                    return iteach;
                }
                return istudies[index];
            }
        }

        bool IEnumerator.MoveNext()
        {
            index++;
            if (index < istudies.Count)
            {
             
                return true;
            }
            Reset();
            return false;

        }

        public void Reset()
        {
            index = -1;
        }

        #endregion

        #region IEnumerable 멤버

        public IEnumerator GetEnumerator()
        {
            return (IEnumerator)this;
        }

        #endregion

-ICloneable 구현

  #region ICloneable 멤버

        public object Clone()
        {
            Console.WriteLine("이름을 입력하세요~");
            string _name = Console.ReadLine();
            return new TeaStu(_name, this.Charisma);
        }

        #endregion

-인덱서 구현

 //인덱서

        public Tea this[string index] 
        {
            get
            {
                foreach (Tea t in stulist)
                {
                    if (t.Name == index)
                    {
                        return t;
                    }
                }
                return null;
            }            
        }

-out,ref 구현

  public double CheckAverage(ref double number)

        {
            int i=0;            
            double sum = 0;
            foreach (Stu st in libarr)
            {
                sum += number - st.IQS;                
            }
            double gap = sum / libarr.Count;            
            number = number - gap;            
            return number;          
        }


'Programing > C#&.Net' 카테고리의 다른 글

어셈블리,메타데이터  (0) 2016.11.30
형식 메타데이터  (0) 2016.11.30
Delegate(대리자)  (0) 2016.11.30
dll만들기 명령 프롬프트 사용  (0) 2016.11.30
c# 기초  (0) 2016.11.30

+ Recent posts