当前位置:编程学习 > C#/ASP.NET >>

反射的应用

 

using System; 

using System.Collections.Generic; 

using System.Text; 

using System.Reflection; 

using Person; 

 

namespace MySchool { 

    /// <summary> 

    /// 注意:因为使用反射进行实例化,当前应用程序并不需要引用类所在的程序集项目 

    /// </summary> 

    class Program { 

        static void Main(string[] args) { 

            //Dll绝对路径(Student) 

            string studentDllPath = @"D:\MySchoolPro\Student\bin\Debug\Student.dll"; 

            //姓名名+类名(Student) 

            string studentClassName = "Student.StudentObject"; 

            //Dll绝对路径(Teacher) 

            string teacherDllPath = @"D:\MySchoolPro\Teacher\bin\Debug\Teacher.dll"; 

            //姓名名+类名(Teacher) 

            string teacherClassName = "Teacher.TeacherObject"; 

            //加载程序集的定义信息(Student)  

            Assembly studentAssembly = Assembly.LoadFile(studentDllPath); 

            //加载程序集的定义信息(Teacher) 

            Assembly teacherAssembly = Assembly.LoadFile(teacherDllPath); 

            //在程序集信息中检索指定类的定义信息(Student) 

            Type studentType = studentAssembly.GetType(studentClassName); 

            //根据检索出的类的定义信息利用反射进行实体化在向上转型(Student) 

            PersonObject student = (PersonObject)Activator.CreateInstance(studentType); 

            //赋值 

            student.Name = "张三"; 

            student.SayHi(); 

            //在程序集信息中检索指定类的定义信息(Teacher) 

            Type teacherType = teacherAssembly.GetType(teacherClassName); 

            //根据检索出的类的定义信息利用反射进行实体化在向上转型(Teacher) 

            PersonObject teacher = (PersonObject)Activator.CreateInstance(teacherType); 

            //赋值 

            teacher.Name = "李四"; 

            teacher.SayHi(); 

            Console.ReadLine(); 

        } 

    } 

 

using System; 

using System.Collections.Generic; 

using System.Text; 

 

namespace Person { 

    /// <summary> 

    /// 父类 

    /// </summary> 

    public class PersonObject { 

 

        private string name; 

 

        public string Name { 

            get { return name; } 

            set { name = value; } 

        } 

 

        public virtual void SayHi() { 

 

        } 

 

    } 

 

using System; 

using System.Collections.Generic; 

using System.Text; 

using Person; 

 

namespace Student { 

    /// <summary> 

    /// 子类 

    /// </summary> 

    public class StudentObject : PersonObject { 

        public override void SayHi() { 

            Console.WriteLine("大家好我是学员叫!{0}", this.Name); 

        } 

    } 

using System; 

using System.Collections.Generic; 

using System.Text; 

using Person; 

 

namespace Teacher { 

    /// <summary> 

    /// 子类 

    /// </summary> 

    public class TeacherObject : PersonObject { 

        public override void SayHi() { 

            Console.WriteLine("大家好我是教员{0}", this.Name); 

        } 

    } 

}   

 

摘自 幸福的猪的专栏

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,