It is often seen that in some VB examples, system functions (mostly COM objects) can be called directly using a Createobject, such as user settings and network settings. Although the Createobject function can be called using the namespace method of VB in C #, this method is useless, because all the methods contained in the generated object cannot be used. In C #, you can directly use the Add reference method to call some objects, provided that you know which reference to add.
When I searched through the Internet and found many examples of VB successfully called with Createobject, but the C # example was hard to find, I simply used a method similar to VB, which is very simple. Otherwise, we will continue to make a haystack in the network.
In C #, The Createobject-like method is system. activator. createinstance. Subsequent object function calls can be implemented through the invokemember method.
For example, the source code in VB is as follows:
This method is called late-bind. For the differences between early binding and later binding, see 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
The code for converting to C # is as follows:
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 });
}
There are methods and attribute call settings, which are very simple.
The actual example is as follows:
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 );
}
This activator. createinstance method can also be used to create an instance and call some interface methods. After all, the interface must be called by an instance.
You can refer to the source code in another article of mine.
Http://www.cnblogs.com/phytan/archive/2007/07/11/814474.html
Implement the Createobject method in VB in C #