简体   繁体   English

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

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

I am looking to convert some VB6/COM+ code to C#/COM+ 我希望将一些VB6 / COM +代码转换为C#/ COM +

However where in VB6 or VB.NET I have: 但是在VB6或VB.NET中,我有:

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

In C# it seems like I have to do the following: 在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);

Is there a way of getting c# to not have to use the InvokeMember function and just call the function directly? 有没有办法让c#不必使用InvokeMember函数直接调用函数?

Is there a way of getting c# to not have to use the InvokeMember function and just call the function directly? 有没有办法让c#不必使用InvokeMember函数直接调用函数?

Yes, as of C# 4 with dynamic typing : 是的,从动态类型的C#4开始:

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. 它在CreateObject部分中仍然更加冗长,但如果需要,您可以始终将其包装在方法调用中。 (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 .) 可能有一个我不知道的现有调用,或者你可以尝试找到VB在这种情况下调用的任何东西 - 我不知道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 . 在幕后,两种情况都会发生同样的事情 - 它仍然没有静态绑定那么快,但它几乎肯定足够快。

Yes, you can use the dynamic keyword 是的,您可以使用dynamic关键字

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM