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);
}
}
}
摘自 幸福的豬的專欄