Home > OS >  How do I make a type of a System.Func with dynamic type arguments
How do I make a type of a System.Func with dynamic type arguments

Time:09-24

I have

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

but the compiler doesn't like the unspecialized Func. Is there a way to spell this out so I can get the generalized type to specialized dynamically.

I can't replace with a directly specialized Func because I don't know my own types at compile time. Reflection.Emit is involved; trying to write typeof(Func<something, something>, int) is impossible.

The exact same construct appears a few lines down with

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

CodePudding user response:

You have to know the arity (number of type parameters) when you do this. The feature is known as an "open" or "unbound" generic in the language specification. Here's the code.

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

I also took the liberty of removing the array initializer since MakeGenericType is params.

  • Related