【发布时间】:2011-05-13 15:15:30
【问题描述】:
我正在尝试动态创建 COM 对象、调用 COM 方法并设置 COM 属性。 COM 类是一个 VB6 ActiveX DLL。该实现与本页http://msdn.microsoft.com/en-us/library/ms973800.aspx中的VB6代码完全相同。
简而言之,项目是PhysServer,类名是Temperature,它有两个属性Celsius和Fahrenheit和两个方法GetCelsius()和GetFahrenheit()。
我已经运行regsvr32 将ActiveX DLL 注册到计算机。 ProgID 是PhysServer.Temperature。
我有三个代码块
代码块 1(有效)
Option Explicit Off
Option Strict Off
...
Dim objType = Type.GetTypeFromProgID("PhysServer.Temperature")
Dim comObj = Activator.CreateInstance(objType)
comObj.Celsius = 100
Dim f As Double = comObj.GetFahrenheit()
Console.WriteLine(f) ' shows 212
代码块 2(有效)
Option Explicit On
Option Strict On
...
Dim objType = Type.GetTypeFromProgID("PhysServer.Temperature")
Dim comObj = Activator.CreateInstance(objType)
Microsoft.VisualBasic.CallByName(comObj, "Celsius", CallType.Let, 100)
Dim f As Double = CDbl(Microsoft.VisualBasic.CallByName(comObj, "GetFahrenheit", CallType.Method, Nothing))
Console.WriteLine(f) ' shows 212
代码块 3(不起作用)
Option Explicit On
Option Strict On
...
Dim objType = Type.GetTypeFromProgID("PhysServer.Temperature")
Dim comObj = Activator.CreateInstance(objType)
Dim f As Double = CDbl(objType.InvokeMember("GetFahrenheit", Reflection.BindingFlags.InvokeMethod, Nothing, comObj, Nothing))
Console.WriteLine(f) ' shows the default value of GetFahrenheit '
objType.InvokeMember("Celsius", Reflection.BindingFlags.SetField Or Reflection.BindingFlags.InvokeMethod, Nothing, comObj, New Object() {100}) ' throws exception: Number of parameters specified does not match the expected number '
f = CDbl(objType.InvokeMember("GetFahrenheit", Reflection.BindingFlags.InvokeMethod, Nothing, comObj, Nothing))
Console.WriteLine(f)
我了解代码块 1 和代码块 2。但是,我如何使用代码块 3 之类的反射设置 COM 对象?由于某些原因,我无法使用代码块 1 和代码块 2。所以唯一的方法是代码块 3……但它不起作用。
有人知道Code Block 3 的解决方案吗?谢谢!
【问题讨论】: