简体   繁体   English

C# 动态泛型参数

[英]C# dynamic generic parameter

when I write a function with a generic like this当我用这样的通用写一个 function

Task<ResultModel<bool>> CancelScheduledTask<T>(string scheduledTaskId, int year, int week) where T : TaskModel;

You have to provide the generic, because it can't be derived from the parameters您必须提供泛型,因为它不能从参数派生

    switch (TaskType)
    {
        case Schedule.ROUTINE:
            cancelRoutineResult = await _taskRepository.CancelScheduledTask<RoutineTask>(TaskId, Year, Week);
            break;

        case Schedule.EVENT:
            cancelRoutineResult = await _taskRepository.CancelScheduledTask<EventTask>(TaskId, Year, Week);
            break;
    }  

Would it be possible to write this without the switch of an if else statement?是否可以在没有 if else 语句的 switch 的情况下编写这个? something like this example which doesn't work类似这个例子的东西不起作用

await _taskRepository.CancelScheduledTask<TaskType.TypeOfTask()>(TaskId, Year, Week);

public static Type TypeOfTask(this string taskType)
    {
        switch (taskType)
        {
            case Schedule.ROUTINE:
                return typeof(ScheduledRoutineModel);

            case Schedule.EVENT:
                return typeof(ScheduledEvent);

            default:
                return null;
        }
    }

If not performance dependent,如果不依赖于性能,

MethodInfo methodInfo = _taskRepository.GetType().GetMethod("CancelScheduledTask").MakeGenericMethod(TaskType.TypeOfTask());
await (methodInfo.Invoke(_taskRepository, new[] { TaskId, Year, Week }) as Task<ResultModel<bool>>);

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

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