dimanche 10 juillet 2016

Advice on calling method dynamically and returning corresponding type

I have many DataObjects that all inherit from a particular class, and these DataObjects each have similar methods that make API calls. I am trying to write an abstract method(s) that will allow me to accept input of API paths and request-method-types ("Get", "Put", "Post", etc.) to make the appropriate API call, and return an object of that type.

Note: I since I will be making API calls I will need to ensure async/await is possible.

This is non-working code describing what I'd like to do:

var dict = Dictionary<Tuple<string, string>, Action>>
{
    //many key/value pairs of RequestMethodType/APIPath tuple keys 
    //and API calling method values
};

public T APICaller<T>(string requestMethodType, string path)
{
    //make tuple of rmt and path
    //use tuple to get API calling Action value from dictionary
    //invoke method and return object of correct type
}

I've done a lot of searching over the past few days, and here are some options I am trying/considering:

  1. Use a Dictionary, Action> to map the input to the method. -issue with void lambda, struggling to return proper type

  2. Use C# Generics to call API and return correct DataObject -Ran into issue where I couldn't return a dynamic type

  3. Use reflection to make generic method in attempts to solve #2

  4. Using dyanmic keyword to allow type to be determined at runtime

*I have also tried of mapping the RequestMethodType/Path tuples to a return type, then using the return type as the return type for a generic method making the API call. When trying this I couldn't get past an error saying I was using a variable when a type was expected. (solve by using reflection??)

Here are some links for similar questions I have read:

C# Is it possible to pass a type into a method and have the method return an object of that type?

How do I use reflection to call a generic method?

generic class, how to set the type in runtime? -as well as many, many more.





Aucun commentaire:

Enregistrer un commentaire