C#中實現VB中的CreateObject方法

來源:互聯網
上載者:User

標籤:style   blog   http   io   os   使用   ar   div   sp   

經常看到有些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

C#中實現VB中的CreateObject方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.