Why I cannot use Type.GetType() in generics?

前端 未结 3 831
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 20:49

I am trying to get rid of some references by using string representation of certain types. But compiler is not letting me do it the way I want in case of generic methods. I

3条回答
  •  时光说笑
    2021-01-15 20:52

    You can use Type.MakeGenericType. Example:

    Type.GetType("YourGenericType").MakeGenericType(Type.GetType("yourTypeParameter"))
    

    Example for a List with a typeparameter determined from a string:

    typeof(List<>).MakeGenericType(Type.GetType("System.String"))
    

    This gives you the same as

    typeof(List)
    

    But you still can't use a Type instance to call Enumerable.OfType. You could use something like this instead:

    foreach (var component in container.Components.Where(o => o.GetType().IsAssignableFrom(yourType))) 
    {
        //...
    }
    

    Of course, this get's messy quickly, so I would consider changing your approach. Why do you wan't to use strings?

提交回复
热议问题