VB CreateObject转C#

时间:2024-09-28 20:03:02

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() Dim numberOfTasks
numberOfTasks = taskCollection.Count If numberOfTasks = 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 ""
taskState = "Unknown"
Case ""
taskState = "Disabled"
Case ""
taskState = "Queued"
Case ""
taskState = "Ready"
Case ""
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[] { });
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部分
}