2 回答

TA貢獻1875條經(jīng)驗 獲得超5個贊
1.C#中類似 CreateObject 的方法就是 System.Activator.CreateInstance. 后續(xù)的對象函數(shù)的調(diào)用可以通過InvokeMember方法來實現(xiàn)。
如在VB中的源代碼如下:
這種方式叫Late-Bind,關于早期綁定和后期綁定的區(qū)別
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.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});
}
里面有方法,屬性的調(diào)用設定.
實際例子如下,調(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)建實例,并調(diào)用某些接口方法。畢竟接口必須要實例才能調(diào)用。
2.CreateObject和菜單里引用效果是類似的,區(qū)別是:CreateObject是創(chuàng)建并返回一個對 ActiveX 對象的引用,相當于實例化該對象;而引用一個對象之后,尚未實例化,需要你自己定義變量實例化此對象。
引用ActiveX 對象還有一個好處:編寫代碼時會自動出現(xiàn)對象的屬性或方法名稱,便于輸入。

TA貢獻1806條經(jīng)驗 獲得超8個贊
CreateObject和菜單里引用效果是類似的,區(qū)別是:CreateObject是創(chuàng)建并返回一個對 ActiveX 對象的引用,相當于實例化該對象;而引用一個對象之后,尚未實例化,需要你自己定義變量實例化此對象。
引用ActiveX 對象還有一個好處:編寫代碼時會自動出現(xiàn)對象的屬性或方法名稱,便于輸入。
添加回答
舉報