VB CreateObject转C#
C#调用方法、函数获取属性大致流程如下:
System.Type oType = System.Type.GetTypeFromProgID("SomeClass"); object o = System.Activator.CreateInstance(oType); oType.InvokeMember("SomeMethod", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { arg1, arg2 }); w = oType.InvokeMember("SomeFunction", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { arg1, arg2 }); w = oType.InvokeMember("SomeGet", System.Reflection.BindingFlags.GetProperty, null, o, null); oType.InvokeMember("SomeSet", System.Reflection.BindingFlags.SetProperty, null, o, new object[] { w });
示例:VB.NET 获取计划任务列表
Dim service = CreateObject("Schedule.Service") Call service.Connect() ' Get the task folder that contains the tasks. Dim rootFolder rootFolder = service.GetFolder("\") Dim taskCollection taskCollection = rootFolder.GetTasks(0) Dim numberOfTasks numberOfTasks = taskCollection.Count If numberOfTasks = 0 Then Debug.Print("No tasks are registered.") Else Debug.Print("Number of tasks registered: " & numberOfTasks) Dim registeredTask For Each registeredTask In taskCollection Debug.Print("Task Name: " & registeredTask.Name) Dim taskState Select Case registeredTask.State Case "0" taskState = "Unknown" Case "1" taskState = "Disabled" Case "2" taskState = "Queued" Case "3" taskState = "Ready" Case "4" taskState = "Running" Case Else taskState = "Unknown" End Select Debug.Print(" Task State: " & taskState) Next End If
翻译为C#:
var typeofScheduleService = System.Type.GetTypeFromProgID("Schedule.Service"); var service = System.Activator.CreateInstance(typeofScheduleService); typeofScheduleService.InvokeMember("Connect", System.Reflection.BindingFlags.InvokeMethod, null, service, new object[] { }); var rootFolder = typeofScheduleService.InvokeMember("GetFolder", System.Reflection.BindingFlags.InvokeMethod, null, service, new object[] { @"\" }); var taskCollection = typeofScheduleService.InvokeMember("GetTasks", System.Reflection.BindingFlags.InvokeMethod, null, rootFolder, new object[] { 0 }); var numberOfTasks = int.Parse(typeofScheduleService.InvokeMember("Count", System.Reflection.BindingFlags.GetProperty, null, taskCollection, new object[] { }).ToString()); foreach(var task in taskCollection as IEnumerable) { var taskName = typeofScheduleService.InvokeMember("Name", System.Reflection.BindingFlags.GetProperty, null, task, new object[] { }).ToString(); var taskState = int.Parse(typeofScheduleService.InvokeMember("State", System.Reflection.BindingFlags.GetProperty, null, task, new object[] { }).ToString()); //略去switch部分 }
桂棹兮兰桨,击空明兮溯流光。