c# Creating an unknown generic type at runtime

前端 未结 2 1107
时光取名叫无心
时光取名叫无心 2020-11-30 11:44

So I have a class that is a generic and it may need to, inside a method of its own, create an instance of itself with a different kind of generic, whose type is obtained thr

相关标签:
2条回答
  • 2020-11-30 11:57

    I think you're looking for the MakeGenericType method:

    // Assuming that Property.PropertyType is something like List<T>
    Type elementType = Property.PropertyType.GetGenericArguments()[0];
    Type repositoryType = typeof(GenericRepository<>).MakeGenericType(elementType);
    var repository = Activator.CreateInstance(repositoryType);
    
    0 讨论(0)
  • 2020-11-30 12:02
    Activator.CreateInstance(typeof(GenericRepository<>).MakeGenericType(new Type[] { Property.GetTYpe() }))
    
    0 讨论(0)
提交回复
热议问题