【问题标题】:How do I make a type of a System.Func with dynamic type arguments如何使用动态类型参数创建 System.Func 类型
【发布时间】:2021-09-23 20:22:36
【问题描述】:

我有

    Type tsomething = /* ... */ ;
    Type comparer = typeof(Func).MakeGenericType(new Type[]{tsomething, tsomething, int});

但编译器不喜欢未专门化的Func。有没有办法把这个拼出来,这样我就可以动态地专门化泛化类型。

我不能用直接专用的 Func 替换,因为我在编译时不知道自己的类型。涉及Reflection.Emit;试图写typeof(Func<something, something>, int) 是不可能的。

完全相同的结构出现在下面几行

    il.DeclareLocal(typeof(IEnumerator).MakeGenericType(new Type[]{tsomething}));

【问题讨论】:

    标签: c# reflection reflection.emit


    【解决方案1】:

    执行此操作时,您必须知道 arity(类型参数的数量)。该功能在语言规范中称为“开放”或“未绑定”泛型。这是代码。

    Type tsomething = typeof(string) ;
    Type comparer = typeof(Func<,,>).MakeGenericType(tsomething, tsomething, typeof(int));
    

    我还冒昧地删除了数组初始值设定项,因为 MakeGenericTypeparams

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 2015-06-29
      • 2011-12-21
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多