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

前端 未结 3 833
伪装坚强ぢ
伪装坚强ぢ 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<string>)
    

    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?

    0 讨论(0)
  • 2021-01-15 20:54

    You want this:

    foreach (var component in container.Components.OfType<MyNamespace.MyType>()) {
    ...
    }
    

    Problem is you have to use the actual type expression in generics, not a string. You could construct the type using reflection if you really need to use the string.

    0 讨论(0)
  • 2021-01-15 21:06

    You can't use a variable in the place of the generic type argument (between < and >). It has to be a type determined at compile time.

    But in your example this is already the case. Can't you just use

    foreach (var component in container.Components.OfType<MyNamespace.MyType>()) {
    ...
    }
    
    0 讨论(0)
提交回复
热议问题