How to get open generic type from string

I have an array of Type [], and I want to get a type of Func, where T1, T2, etc. match the types in the array. The array is not fixed in size, but it is assumed that the type is available at run time (16 in .NET 4, 4 in .NET 3.5).

In .NET 4, I can do this and it works:

Type GetFuncType(Type typeRet, Type[] types)
{
    return Type.GetType(string.Format("System.Func`{0}", types.Length + 1))
                  .MakeGenericType(types.Concat(new Type[] { typeRet } ).ToArray())
}

However, in .NET 3.5, the Type.GetType type for an open type is generated with an error, returning NULL.

Is there a way to make this work in .NET 3.5? My only thoughtful atm is to create a string for a close generic type.

+3
source share
2 answers

The preferred way to do this is to use Expression.GetFuncType(Type[])and Expression.GetActionType(Type[]). In the case of func, the latter Typeis the return, therefore:

Array.Resize(ref types, (types == null ? 0 : types.Length) + 1);
types[types.Length - 1] = typeRet;
return Expression.GetFuncType(types);
+4

Marc , , , . , .

Func` {0}, . , , , ( ):

typeof(Func<>).Assembly.GetType(string.Format("Func`{0}", types.Length+1));

typeof(Func<>).Assembly - , , Func.

0

All Articles