在.net上用字符串動態創建控件是通過反射來實現。
首先,利用system.type.gettype方法,獲得字符串中指定的控件的類型實例。
這里需要注意這個字符串的語法,根據msdn的解釋:
不對數組或 com 類型執行搜索,除非已將它們加載到可用類表中。
typename 可以是簡單的類型名、包含命名空間的類型名,或是包含程序集名稱規范的復雜名稱。
如果 typename 只包含 type 的名稱,則此方法先是在調用對象的程序集中進行搜索,然后在 mscorlib.dll 程序集中進行搜索。如果 typename 用部分或完整的程序集名稱完全限定,則此方法在指定的程序集中進行搜索。
assemblyqualifiedname 可以返回完全限定的類型名稱(包含嵌套類型和程序集名稱)。所有支持公共語言運行庫的編譯器將發出嵌套類的簡單名稱,并且當被查詢時,反射依照下列約定構造一個 mangled 名稱。
例如,類的完全限定名可能類似于如下形式:
topnamespace.subnamespace.containingclass+nestedclass,myassembly
但是直接使用type.gettype("system.windows.forms.textbox")獲得type是null。這是因為,windows.forms程序集是公有的程序集,是位于程序集緩存中的,而這個程序集有不同的版本,為了確定使用的版本,我們不僅要提供程序集的名稱,還要提供程序集的版本和強名稱。照這個思路,在使用的.net framework 1.1上,將這一句寫成type.gettype("system.windows.forms.checkbox, system.windows.forms, version=1.0.5000.0, culture=neutral, publickeytoken=b77a5c561934e089")。現在運行就沒有問題了。問題是我們如何取得所用windows.forms程序集的版本和強名稱?可以用gettype(checkbox).assemblyqualifiedname這樣的語法,一旦得到了這些信息,我們就可以將這些信息用于其它任何控件,因為他們都來自于同一個版本windows.forms程序集。
利用上面說到的方法,現在就可以使用system.activator.createinstance方法來創建一個textbox控件了:
public static void createcontrol(string controltype, form form, int positionx, int positiony)
{
try
{
string assemblyqualifiedname = typeof(system.windows.forms.form).assemblyqualifiedname;
string assemblyinformation = assemblyqualifiedname.substring(assemblyqualifiedname.indexof(","));
type ty = type.gettype(controltype + assemblyinformation);
control newcontrol = (control)system.activator.createinstance(ty);
form.suspendlayout();
newcontrol.location = new system.drawing.point(positionx, positiony);
newcontrol.name = ty.name + form.controls.count.tostring();
form.controls.add(newcontrol);
form.resumelayout();
}
catch(exception ex)
{
throw ex;
}
}
調用: createcontrol("system.windows.forms.textbox", this, 10, 10);
新聞熱點
疑難解答
圖片精選