Why is the C# CreateObject so much more verbose than VB.NET?

两盒软妹~` 提交于 2019-12-22 04:15:09

问题


I am looking to convert some VB6/COM+ code to C#/COM+

However where in VB6 or VB.NET I have:

Dim objAdmin
objAdmin = Server.CreateObject("AppAdmin.GUI")
objAdmin.ShowPortal()

In C# it seems like I have to do the following:

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);

Is there a way of getting c# to not have to use the InvokeMember function and just call the function directly?


回答1:


Is there a way of getting c# to not have to use the InvokeMember function and just call the function directly?

Yes, as of C# 4 with dynamic typing:

dynamic admin = Activator.CreateInstance(Type.GetTypeFromProgID("AppAdmin.GUI"));
admin.ShowPortal();

It's still more verbose in the CreateObject part, but you could always wrap that up in a method call if you wanted. (There may be an existing call I'm not aware of, or you could try to find whatever VB is calling in that case - I don't know the details of Server.CreateObject.)

Note that dynamic typing is richer than just making reflection simpler, but it certainly does that. Behind the scenes, the same kind of thing will be happening in both cases though - it's still not going to be as fast as static binding, but it's almost certainly fast enough.




回答2:


Yes, you can use the dynamic keyword

dynamic objAdmin = System.Activator.CreateInstance(objAdminType);
objAdmin.ShowPortal();



回答3:


If you have access to the actual class type, you can do it as follows:

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


来源:https://stackoverflow.com/questions/12319422/why-is-the-c-sharp-createobject-so-much-more-verbose-than-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!