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