C#中實現VB中的CreateObject方法


經常看到有些VB的例子中直接用個CreateObject就可調用系統功能(大多是COM對象),像用戶設定,網絡設定等等。雖然C#中可以通過使用VB的命名空間的方法來調用CreateObject函數,但是這樣比較沒什么用,因為生成的對象的所帶有的方法都不能使用。C#中還可以直接用添加引用的方式來調用一些對象,前提是你知道該添加哪個引用。
當我上網搜索,已經搜索到很多VB的成功用CreateObject調用的例子,C#的例子卻很難找到的時候,就干脆用類似VB的方法算了,很簡單。免得繼續在網絡中大海撈針了。

C#中類似 CreateObject 的方法就是 System.Activator.CreateInstance.  后續的對象函數的調用可以通過InvokeMember方法來實現。

如在VB中的源代碼如下
這種方式叫Late-Bind,關於早期綁定和后期綁定的區別見 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 


轉換成C#的代碼如下所示:

public void TestLateBind() 

        System.Type oType = System.Type.GetTypeFromProgID("SomeClass"); 
        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}); 


里面有方法,屬性的調用設定,很簡單。

實際例子如下,調用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方法還可以用來創建實例,並調用某些接口方法。畢竟接口必須要實例才能調用。 
可以參考我的另外一個隨筆里面的源代碼
http://www.cnblogs.com/phytan/archive/2007/07/11/814474.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM