問題:
在一個主程序中調用一個類,假設為類名A,調用這個A的方法,但當用戶覺得調用這個A的方法不夠准確,於是設計了另一個類,類名為B,B也實現同一個方法名,但實現的具體過程不一樣,問題是:能否通過界面化的方式人工設置調用了B類而不是以前的A類了,不用去修改主程序的源代碼,A類可能也是存在的,因為它可以作為B類的父類,問題主要在於B類的類名B,是在將來命名的,可以說是隨機的,通過什麼樣的方式能實現這種調用 ?

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;


namespace ConsoleApplication1


...{

class Program


...{

static void Main(string[] args)


...{

//加載當前的程序集(WindowsApplication1.exe是當前的程序的exe)

System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom("ConsoleApplication1.exe");

Type[] mytypes = ass.GetTypes();//獲取程序集的類型

Console.WriteLine("選擇你需要調用的類:");

int index = 0;

foreach (Type t in mytypes)//列出程序集中的所有類


...{

if (t.IsClass)//判斷該類型是不是類

Console.WriteLine(index + " " + t.Name);

index++;

}

int selectIndex = int.Parse(Console.ReadLine());//按照要求,界面化的方式人工設置調用,選擇你需要的類

Type type = mytypes[selectIndex];


//創建程序集類型一個實例,as操作符來判斷該類是否支持指定的接口,如果不支持將給接口變量賦空值(null)

IMyInterface myInterface = System.Activator.CreateInstance(type) as IMyInterface;

if (myInterface != null)

Console.Write("你所調用函數的返回值是:"+myInterface.getInformation());

else

Console.WriteLine("該類不支持指定接口!");

Console.Read();

}

}

//編寫一個接口,接口裡的方法可以由不同的類來繼承實現

public interface IMyInterface


...{

string getInformation();

}

public class A : IMyInterface


...{

public string getInformation()//實現方式一


...{

return "A.getInformation()";

}

}

//類名可以是將來命名,也可以是隨機的,需要調用時可以通過反射(Reflection)來獲取

public class B : IMyInterface


...{

public string getInformation()//實現方式二


...{

return "B.getInformation()";

}

}


}
http://topic.csdn.Net/u/20071006/15/cf4a9748-af81-4d84-b8b4-c2f38deb923a.Html