慕田峪4524236
1.C#中类似 CreateObject 的方法就是 System.Activator.CreateInstance. 后续的对象函数的调用可以通过InvokeMember方法来实现。如在VB中的源代码如下:这种方式叫Late-Bind,关于早期绑定和后期绑定的区别Dim o As Object = CreateObject("SomeClass")o.SomeMethod(arg1, arg2)w = o.SomeFunction(arg1, arg2)w = o.SomeGeto.SomeSet = wEnd 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方法还可以用来创建实例,并调用某些接口方法。毕竟接口必须要实例才能调用。2.CreateObject和菜单里引用效果是类似的,区别是:CreateObject是创建并返回一个对 ActiveX 对象的引用,相当于实例化该对象;而引用一个对象之后,尚未实例化,需要你自己定义变量实例化此对象。引用ActiveX 对象还有一个好处:编写代码时会自动出现对象的属性或方法名称,便于输入。