【问题标题】:Variable generic type count runtime reflection变量泛型类型计数运行时反射
【发布时间】:2021-05-03 11:44:32
【问题描述】:

现在我有这个代码:

//some Method detection here..

var methodParams = method.GetParameters();
Type actionType = null;

switch(methodParams.Length)
{
    case 1:
        actionType = typeof(Action<>);
        break;

    case 2:
        actionType = typeof(Action<,>);
        break;

    case 3:
        actionType = typeof(Action<,,>);
        break;

    case 4:
        actionType = typeof(Action<,,,>);
        break;

    case 5:
        actionType = typeof(Action<,,,,>);
        break;
}

var actionGenericType = actionType.MakeGenericType(methodParams.Select(x => x.ParameterType).ToArray());

我不喜欢这个 switch 语句,但我还没有找到一种方法来根据参数的数量(或基于任何运行时 int)选择 Action 泛型重载。

有没有更优雅的方式/oneliner 来做这样的事情?

我不想使用调度表。

【问题讨论】:

    标签: c# reflection switch-statement refactoring variable-assignment


    【解决方案1】:

    正如我在调试器中看到的,actionType 可以通过以下方式获得:

    var actionType = Type.GetType("System.Action`" + methodParams.Length);
    

    【讨论】:

    • 顺便说一句,这是一个反勾号(QWERTY 键盘上的1 上方)
    • 没错,SO标记中使用了相同的符号:-)
    猜你喜欢
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 2020-09-02
    相关资源
    最近更新 更多