Implementing Generic Type Inference in C# reflectively

后端 未结 1 373
挽巷
挽巷 2021-01-15 08:54

I need to do some generic type inference for a scripting language implementation and I am wondering if I am missing some straightforward approach. For the moment let me jus

相关标签:
1条回答
  • 2021-01-15 09:58

    So, I believe I have implemented this successfully going on the assumption that you have to reify the types for assignability comparison. As near as I can tell there is not even a way to extract the base type from a generic type in order to perform assignment checks yourself. So what I ended up doing is using GetGenericArguments to traverse the method parameter type and the argument type in parallel, performing sanity checks at each step (number of generic params match, etc.) and once ultimately finding the "naked" generic type param, noting the corresponding (inferred) type in the argument. You can determine that you've found a type param using IsGenericParameter. Then, weirdly, you have to save those types aside and use them to instantiate the method by passing them in a particular order to MakeGenericMethod. The order is provided for you by a property on Type itself, GenericParameterPosition, (again, weird) but a simple orderby sorts them out. After that all of the normal rules seem to apply.

    -Pat

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