制作多种类型的泛型 [英] Making Generics with many types
问题描述
我有一段代码,有时候我需要创建一个新的泛型类型,但是泛型参数数量不确定。例如:
I have a chunk of code where sometimes I need to create a new generic type, but with an unknown number of generic parameters. For example:
public object MakeGenericAction(Type[] types)
{
return typeof(Action<>).MakeGenericType(paramTypes);
}
问题是如果我的数组中有多个Type,那么该程序将崩溃。在短期内,我想出了这样的一个止损。
The problem is that if I have more than one Type in my array, then the program will crash. In the short term I have come up with something like this as a stop-gap.
public object MakeGenericAction(Type[] types)
{
if (types.Length == 1)
{
return typeof(Action<>).MakeGenericType(paramTypes);
}
else if (types.Length ==2)
{
return typeof(Action<,>).MakeGenericType(paramTypes);
}
..... And so on....
}
这确实有效,并且很容易覆盖我的场景,但它看起来非常黑。有没有更好的方法来处理这个问题?
This does work, and is easy enough to cover my scenarios, but it seems really hacky. Is there a better way to handle this?
推荐答案
在这种情况下,是的:
Type actionType = Expression.GetActionType(types);
这里的问题是您可能会使用DynamicInvoke,这很慢。
The problem here though is that you will probably be using DynamicInvoke which is slow.
An Action< object []>
,那么索引访问可能优于 Action< ...> ;
用DynamicInvoke
An Action<object[]>
then access by index may outperform an Action<...>
invoked with DynamicInvoke
这篇关于制作多种类型的泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!