天天看點

使用反射實作延遲綁定

反射允許我們在編譯期或運作時擷取程式集的中繼資料,通過反射可以做到:

● 建立類型的執行個體

● 觸發方法

● 擷取屬性、字段資訊

● 延遲綁定

......

如果在編譯期使用反射,可通過如下2種方式擷取程式集Type類型:

1、Type類的靜态方法

Type type = Type.GetType("somenamespace.someclass");

2、通過typeof

Type type = typeof(someclass);

如果在運作時使用反射,通過運作時的Assembly執行個體方法擷取Type類型:

Type type = asm.GetType("somenamespace.someclass");

  擷取反射資訊

有這樣的一個類:

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public float Score { get; set; }

        public Student()
        {
            this.Id = -1;
            this.Name = string.Empty;
            this.Score = 0;
        }

        public Student(int id, string name, float score)
        {
            this.Id = id;
            this.Name = name;
            this.Score = score;
        }

        public string DisplayName(string name) 
        {
            return string.Format("學生姓名:{0}", name);
        }

        public void ShowScore()
        {
            Console.WriteLine("學生分數是:" + this.Score);
        }
    }      

通過如下擷取反射資訊:

static void Main(string[] args)
        {
            Type type = Type.GetType("ConsoleApplication1.Student");
            //Type type = typeof (Student);

            Console.WriteLine(type.FullName);
            Console.WriteLine(type.Namespace);
            Console.WriteLine(type.Name);

            //擷取屬性
            PropertyInfo[] props = type.GetProperties();
            foreach (PropertyInfo prop in props)
            {
                Console.WriteLine(prop.Name);
            }

            //擷取方法
            MethodInfo[] methods = type.GetMethods();
            foreach (MethodInfo method in methods)
            {
                Console.WriteLine(method.ReturnType.Name);
                Console.WriteLine(method.Name);
            }
            Console.ReadKey();
        }      

  延遲綁定

在通常情況下,為對象執行個體指派是發生在編譯期,如下:

Student stu = new Student();
stu.Name = "somename";      

而"延遲綁定",為對象執行個體指派或調用其方法是發生在運作時,需要擷取在運作時的程式集、Type類型、方法、屬性等。

//擷取運作時的程式集
            Assembly asm = Assembly.GetExecutingAssembly();

            //擷取運作時的Type類型
            Type type = asm.GetType("ConsoleApplication1.Student");

            //擷取運作時的對象執行個體
            object stu = Activator.CreateInstance(type);

            //擷取運作時指定方法
            MethodInfo method = type.GetMethod("DisplayName");
            object[] parameters = new object[1];
            parameters[0] = "Darren";

            //觸發運作時的方法
            string result = (string)method.Invoke(stu, parameters);
            Console.WriteLine(result);
            Console.ReadKey();