2011-06-07 48 views
6

我有一段代碼,有時需要創建一個新的泛型類型,但泛型參數數量未知。例如:製作多種類型的泛型

public object MakeGenericAction(Type[] types) 
{ 
    return typeof(Action<>).MakeGenericType(paramTypes); 
} 

問題是,如果我的數組中有多個Type,那麼程序將崩潰。在短期內,我已經想出了這樣的一個缺口。

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.... 
} 

這是行不通的,而且很容易覆蓋我的方案,但它看起來很詭異。有沒有更好的方法來處理這個問題?

回答

5

在這種情況下,是:

Type actionType = Expression.GetActionType(types); 

雖然這裏的問題是,你可能會被使用DynamicInvoke這是緩慢的。

Action<object[]>然後通過索引訪問可能會優於其他DynamicInvoke調用的Action<...>

+1

美麗的,優雅的解決方案(或至少與反射型仿製藥一樣多) – KeithS 2011-06-07 17:09:52

+1

非常好。如果陣列中的類型超過16種,會發生什麼情況?除了警方將您的所有電子設備移除之外。 – IndigoDelta 2011-06-07 17:11:23

+0

@IndigoDelta齒輪會掉出來; p – 2011-06-07 17:12:26

0
Assembly asm = typeof(Action<>).Assembly; 
Dictionary<int, Type> actions = new Dictionary<int, Type>; 
foreach (Type action in asm.GetTypes()) 
    if (action.Name == "Action" && action.IsGenericType) 
     actions.Add(action.GetGenericArguments().Lenght, action) 

,那麼你可以使用actions字典來快速找到正確的類型:

public Type MakeGenericAction(Type[] types) 
{ 
    return actions[types.Lenght].MakeGenericType(paramTypes); 
}