(C#기초)반사 이해

4226 단어
이 지식점은 매우 기초적이다.
코드
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dazilianxi
{
   public class book:IComparable
    {
       private int price;
       private string title;
       public book() { }
       public book(int price ,string title)
       {
           this.price = price;
           this.title = title;
       }
       public int Price
       {
           get { return this.price; }
       }

       public string Title {
           get { return this.title; }
       }


       #region IComparable   

       public int CompareTo(object obj)
       {
           book mbook = (book)obj;
           return this.Price.CompareTo(mbook.Price);
       }
       public string DisplayName(string name)
       {
           return string.Format("    :{0}", name);
       }

       #endregion
    }
}

 
실행 중인 main 코드:
/*
            Type type = Type.GetType("dazilianxi.book");
            Console.WriteLine(type.Name);
            Console.WriteLine(type.FullName);
            Console.WriteLine(type.Namespace);
            //    
            PropertyInfo[] info = type.GetProperties();
            foreach( PropertyInfo item in info )
            {
                Console.WriteLine(item.Name);
            }

            Console.WriteLine("     ");
            //    
            MethodInfo[] meth = type.GetMethods();
            foreach(MethodInfo me in meth)
            {
                Console.WriteLine(me.ReturnType.Name);
                Console.WriteLine(me.Name);
            }
            */
            book lob = new book( 100,"   ");

            //         
            Assembly asm = Assembly.GetExecutingAssembly();
            //      Type  
            Type type = asm.GetType("dazilianxi.book");

            //          
            object stu = Activator.CreateInstance(type);

            //         
            MethodInfo method = type.GetMethod("DisplayName");
            object[] parameters = new object[1];//      
            parameters[0] = "88lll";//    
          //  parameters[1] = "hello";
            //        
            string result = (string)method.Invoke(stu, parameters);//         
            Console.WriteLine(result);

참조:http://www.cnblogs.com/darrenji/p/3817999.html

좋은 웹페이지 즐겨찾기