Often see some examples of VB directly with a CreateObject can invoke system functions (mostly COM objects), such as user settings, network settings and so on. Although C # can invoke the CreateObject function by using the method of the namespace of VB, this comparison is useless because the method of the generated object cannot be used. In C # You can also invoke objects directly by adding references, provided you know which references to add.
When I search the Internet, has been searching for a lot of VB successful use of CreateObject call examples, C # Examples are difficult to find when, simply using a similar method of VB to forget, very simple. To avoid a needle in the net.
A similar CreateObject method in C # is System.Activator.CreateInstance. Subsequent calls to object functions can be implemented by means of the InvokeMember method.
such as in the VB source code is as follows:
This is called Late-bind, and the difference between early and late binding is shown in 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 to convert to C # looks like this:
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, properties of the call set, very simple.
The actual example is the following, which calls Office functionality:
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 instances and invoke some interface methods. After all, the interface must be an instance to invoke.
can refer to my other essay inside the source code