gpt4 book ai didi

c# - 如何创建具有指定泛型类型的 func 类型?

转载 作者:太空宇宙 更新时间:2023-11-03 17:49:12 25 4
gpt4 key购买 nike

我想用指定的泛型类型参数创建 Func 类型,类似的东西,但只有一个语句

Type create_type(Type[] types)
{
return typeof(Func<>).MakeGenericType(types); // error if types.Length != 1
return typeof(Func<,>).MakeGenericType(types); // error if types.Length != 2
return typeof(Func<,,>).MakeGenericType(types); // error if types.Length != 3
return typeof(Func<,,,>).MakeGenericType(types); // error if types.Length != 4
// ....
}

当然,我可以创建辅助数组:
var func_types = new Type[] { typeof(Func<>), typeof(Func<,>) , //...}

但是这个解决方案对我来说似乎太丑了

注意:类型数组可以很长(最多 15 个),我想找到优雅的解决方案。不幸的是,我正在从元数据创建这种类型,用另一种语言编写

最佳答案

用于 Func 和 Action 的 Expression 类中有静态方法可以完全满足您的要求

Expression.GetFuncType(Type[] types)

Expression.GetActionType(Type[] types)
更多信息在这里: GetFuncType GetActionType

关于c# - 如何创建具有指定泛型类型的 func 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39998567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com