經(jīng)常看到有些VB的例子中直接用個(gè)CreateObject就可調(diào)用系統(tǒng)功能(大多是COM對象),像用戶設(shè)定,網(wǎng)絡(luò)設(shè)定等等。雖然C#中可以通過使用VB的命名空間的方法來調(diào)用CreateObject函數(shù),但是這樣比較沒什么用,因?yàn)樯傻膶ο蟮乃鶐в械姆椒ǘ疾荒苁褂谩#中還可以直接用添加引用的方式來調(diào)用一些對象,前提是你知道該添加哪個(gè)引用。
當(dāng)我上網(wǎng)搜索,已經(jīng)搜索到很多VB的成功用CreateObject調(diào)用的例子,C#的例子卻很難找到的時(shí)候,就干脆用類似VB的方法算了,很簡單。免得繼續(xù)在網(wǎng)絡(luò)中大海撈針了。
C#中類似 CreateObject 的方法就是 System.Activator.CreateInstance. 后續(xù)的對象函數(shù)的調(diào)用可以通過InvokeMember方法來實(shí)現(xiàn)。
如在VB中的源代碼如下:
這種方式叫Late-Bind,關(guān)于早期綁定和后期綁定的區(qū)別見 http://msdn2.microsoft.com/zh-cn/library/0tcf61s1(VS.80).aspx
Public Sub TestLateBind()
Dim o As Object = CreateObject("SomeClass")
o.SomeMethod(arg1, arg2)
w = o.SomeFunction(arg1, arg2)
w = o.SomeGet
o.SomeSet = w
End Sub
轉(zhuǎn)換成C#的代碼如下所示:
public void TestLateBind()
{
System.Type oType = System.Type.GetTypeFrom object o = System.Activator.CreateInstance(oType);
oType.InvokeMember("SomeMethod", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] {arg1, arg2});
w = oType.InvokeMember("SomeFunction", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] {arg1, arg2});
w = oType.InvokeMember("SomeGet", System.Reflection.BindingFlags.GetProperty, null, o, null);
oType.InvokeMember("SomeSet", System.Reflection.BindingFlags.SetProperty, null, o, new object[] {w});
}
里面有方法,屬性的調(diào)用設(shè)定,很簡單。
實(shí)際例子如下,調(diào)用Office功能的:
public void TestLateBind()
{
System.Type WordType = System.Type.GetTypeFromProgID( "Word.application" );
Object word = System.Activator.CreateInstance( wordType );
wordType.InvokeMember( "Visible", BindingFlags.SetProperty, null, word, new Object[] { true } );
Object documents = wordType.InvokeMember( "Documents", BindingFlags.GetProperty, null, word, null );
Object document = documents.GetType().InvokeMember( "Add", BindingFlags.InvokeMethod, null, documents, null );
}
這種Activator.CreateInstance方法還可以用來創(chuàng)建實(shí)例,并調(diào)用某些接口方法。畢竟接口必須要實(shí)例才能調(diào)用。
可以參考我的另外一個(gè)隨筆里面的源代碼
http://www.survivalescaperooms.com/phytan/archive/2007/07/11/814474.html
新聞熱點(diǎn)
疑難解答
圖片精選