c# Creating an unknown generic type at runtime

前端 未结 2 1118
时光取名叫无心
时光取名叫无心 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
    Type elementType = Property.PropertyType.GetGenericArguments()[0];
    Type repositoryType = typeof(GenericRepository<>).MakeGenericType(elementType);
    var repository = Activator.CreateInstance(repositoryType);
    

提交回复
热议问题