mercredi 20 juin 2018

Calling a generic function where the type of the generic function is determined by an input string

I am trying to call a generic function where the type of the generic function is determined by an input string. I want a function that takes in a string, uses reflection to turn that string into a type and then calls a generic function with that type. I have been working with the solution proposed in How do I use reflection to call a generic method? but I just cannot get it to work. Any help would be greatly appreciated.

//This is the generic function(just a simple example function that writes out the incoming type):
public class SelectableRepository
{
    public virtual string GetTypeOfEntity<TEntity>()
    {
        return typeof(TEntity).ToString();
    }
}

//This is the controller that is attempting to call the generic function with the type of "inputString"
public class MyController
{
    public void MyFunction(string inputString)
    {
        //This is how I have been trying to invoke the method but to no avail:
        var myType = Type.GetType("Models.DatabaseModels." + inputString);              //Get the type of the input string
        MethodInfo method = typeof(SelectableRepository).GetMethod("GetTypeOfEntity");  //Get the generic method from SelectableRepository
        MethodInfo genericMethod = method.MakeGenericMethod(myType);                    //Initialize the generic method with the type from the input string
        genericMethod.Invoke(this, null);                                               //Call the method, I'm pretty sure this is wrong
    }
}

//This is an example of a class that could go into the generic method, the inputString would then be "Company"
namespace Models.DatabaseModels
public class Company 
{
    public string Name { get; set; }
}

I put a breakpoint on the genericMethod.Invoke line and looked at the contents of my variables:

myType = {Models.DatabaseModels.Company}
method = {System.String GetTypeOfEntity[TEntity]()}
genericMethod = {System.String GetTypeOfEntity[Company]()} 

I am getting an error on the last line of this code: genericMethod.Invoke(this, null);

The error reads: TargetException: Object does not match target type.

Am I doing something completely wrong?





Aucun commentaire:

Enregistrer un commentaire