Build c# Generic Type definition at runtime

后端 未结 1 1161
一向
一向 2020-12-09 11:25

At present I\'m having to do something like this to build a Type definition at runtime to pass to my IOC to resolve. Simplified:

Type t = Type.GetType(
\"Sys         


        
相关标签:
1条回答
  • 2020-12-09 12:06

    MakeGenericType - i.e.

    Type passInType = ... /// perhaps myAssembly.GetType(
            "ConsoleApplication2.Program+Person")
    Type t = typeof(List<>).MakeGenericType(passInType);
    

    For a complete example:

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    namespace ConsoleApplication2 {
     class Program {
       class Person {}
       static void Main(){
           Assembly myAssembly = typeof(Program).Assembly;
           Type passInType = myAssembly.GetType(
               "ConsoleApplication2.Program+Person");
           Type t = typeof(List<>).MakeGenericType(passInType);
       }
     }
    }
    

    As suggested in the comments - to explain, List<> is the open generic type - i.e. "List<T> without any specific T" (for multiple generic types, you just use commas - i.e. Dictionary<,>). When a T is specified (either through code, or via MakeGenericType) we get the closed generic type - for example, List<int>.

    When using MakeGenericType, any generic type constraints are still enforced, but simply at runtime rather than at compile time.

    0 讨论(0)
提交回复
热议问题