C# สร้าง Object ตอน Runtime โดยการระบุ ชื่อ Class และ Method (2010-03-04)
บางครั้งเราต้องการที่จะสร้าง Class ตอน Runtime โดยการระบุ เฉพาะชื่อ และ method ที่ต้องการจะเรียกตอน Runtime ผมลองผิดลองถูกอยู่หลายวิธี
อันนี้แหระครับเด็ดสุดแล้ว
ผมได้เขียนตัวอย่างการเรียกโดยใช้ Reflection ใน C# นะครับ พร้อมกันนี้ผมก็เขียน Class ที่มีการ Override Method จาก Class แม่
ซึ่งระบะ keyword virtual ไว้ (Polymophism) ยิงปืนนัดเดียวได้นกสองตัว
อันแรกเป็นคลาส Animal , Dog และ Cat ที่มีการทำ Override นะครับ
class Animal
{
public virtual String Say(String myname)
{
return "I am the animal!!!!" + "\n My name is " + myname;
}
}
class Dog : Animal
{
public override string Say(String myname)
{
return "I am a dog and " + base.Say(myname);
}
}
class Cat : Animal
{
public override string Say(String myname)
{
return "I am a cat and " + base.Say(myname);
}
} |
อันนี้เป็นการสร้าง Object ตอน Run
private void button1_Click_1(object sender, EventArgs e)
{
GetInstance("Dog", "Pluto");
GetInstance("Cat", "SaiTao");
}
public void GetInstance(String className, String animalName)
{
//Get the current assembly object
Assembly assembly = Assembly.GetExecutingAssembly();
//Get the name of the assembly (this will include the public token and version number
AssemblyName assemblyName = assembly.GetName();
//Use just the name concat to the class chosen to get the type of the object
Type objType = assembly.GetType(assemblyName.Name + "." + className);
//Create an instance of the type
object obj = Activator.CreateInstance(objType);
object[] mParam = new object[] { animalName };
//invoke Say, passing in one parameters
String str = (String)objType.InvokeMember("Say", BindingFlags.InvokeMethod,
null, obj, mParam);
MessageBox.Show(str);
} |
ตบท้ายด้วยการใช้คุณสมบัติ Polymorphism
|
Animal animal = new Dog(); //animal จะเป็น Object ของ Dog
หรือ
Animal animal = new Cat(); //animal จะเป็น Object ของ Cat
* Class ทาง ขาวมือจะต้อง Inherite มาจาก Class ทางซ้ายมือเสมอนะครับ
|
|