我想動態創建COM對象,調用COM方法並設置COM屬性。 COM類是一個VB6 ActiveX DLL。該實現完全等同於該頁面http://msdn.microsoft.com/en-us/library/ms973800.aspx中的VB6代碼。調用COM屬性和方法
總而言之一句話,該項目是PhysServer
和類名是Temperature
它有兩個屬性Celsius
和Fahrenheit
和兩個方法GetCelsius()
和GetFahrenheit()
。
我已經運行regsvr32
將ActiveX DLL註冊到計算機。 ProgID是PhysServer.Temperature
。
我有代碼的3塊
碼塊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(沒有按't work)
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的解決方案?謝謝!
這不是RCW,他使用了晚期綁定。主知道爲什麼。 – 2010-11-29 19:17:00
謝謝男人......我在網上找到了解決方案。請閱讀我的答案。 – 2010-11-30 04:55:27
@Hans Passant:即使使用IDispatch,它仍然是RCW,當然, – 2010-11-30 23:59:13