Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么C#CreateObject比VB.NET更冗长?_C#_Vb.net_Com - Fatal编程技术网

为什么C#CreateObject比VB.NET更冗长?

为什么C#CreateObject比VB.NET更冗长?,c#,vb.net,com,C#,Vb.net,Com,我想把一些VB6/COM+代码转换成C#/COM+ 但是,在VB6或VB.NET中,我有: Dim objAdmin objAdmin = Server.CreateObject("AppAdmin.GUI") objAdmin.ShowPortal() 在C#中,我似乎必须执行以下操作: object objAdmin = null; System.Type objAdminType = System.Type.GetTypeFromProgID("AppAdmin.GUI"); m_obj

我想把一些VB6/COM+代码转换成C#/COM+

但是,在VB6或VB.NET中,我有:

Dim objAdmin
objAdmin = Server.CreateObject("AppAdmin.GUI")
objAdmin.ShowPortal()
在C#中,我似乎必须执行以下操作:

object objAdmin = null;
System.Type objAdminType = System.Type.GetTypeFromProgID("AppAdmin.GUI");
m_objAdmin = System.Activator.CreateInstance(objAdminType);
objAdminType.InvokeMember("ShowPortal", System.Reflection.BindingFlags.InvokeMethod, null, objAdmin, null);
有没有办法让c#不必使用InvokeMember函数而直接调用该函数?

是的,您可以使用关键字

有没有办法让c#不必使用InvokeMember函数而直接调用该函数

是的,从C#4起:

CreateObject
部分更为详细,但如果需要,您可以随时将其封装在方法调用中。(可能存在我不知道的现有调用,或者您可以尝试查找VB在这种情况下调用的任何调用-我不知道
Server.CreateObject
的详细信息)


注意,动态类型比使反射更简单更丰富,但它确实做到了这一点。但在幕后,这两种情况下都会发生同样的事情——它仍然不会像静态绑定那样快,但几乎可以肯定它已经足够快了。

如果您有权访问实际的类类型,您可以按如下方式操作:

AppAdminClass m_objAdmin = (AppAdminClass)System.Activator.CreateInstance(typeof(AppAdminClass));
m_objAdmin.ShowPortal();

简短回答:因为VB从一开始就是为消费COM对象而设计的,而C#不是。
dynamic admin = Activator.CreateInstance(Type.GetTypeFromProgID("AppAdmin.GUI"));
admin.ShowPortal();
AppAdminClass m_objAdmin = (AppAdminClass)System.Activator.CreateInstance(typeof(AppAdminClass));
m_objAdmin.ShowPortal();