I am building a DSL in C# using expression trees and one of the challenges I am trying to solve is inferring generic types from an input expression. Here is a contrived example:
class GenericThing<T> {
public List<IOption<T>> solveMe;
}
// given the type of some expression, (and assuming types are assignable to each other)
var someExpression = new List<IOption<string>>();
// call a function that can infer the type of generic arguments from `GenericThing<>`
Type reflected = SolveGenericTypes(typeof(GenericThing<>), "solveMe", someExpression.GetType()));
// use that type to create an instance of GenericThing<string>
object instance = Activator.CreateInstance(reflected);
How could I implement SolveGenericTypes()
to 'solve' for T? (Bonus, also solve for multiple generic arguments) I would need the function to work not just for this case, but basically take any generic type definition and any concrete type (assume there are no typechecking errors) and return a type that can be instantiated.
Thanks!
Aucun commentaire:
Enregistrer un commentaire