jeudi 11 octobre 2018

C# - Using reflection with JsonSchema4.FromTypeAsync

[INTRO] I know there are about a zillion QA about generics and reflections everywhere, but it's becoming a blackhole to me, and I'm only getting more lost the more I read!!

What i need to do is simple, and I'm amazed that it hasn't been addressed before.

[SAMPLE] Consider the following snippit:

public async Task<string> generateJsonSchema(string model)
{
    try
    {
        string modelName = "Models." + model;
        Type t = Type.GetType(modelName, false);
        JsonSchema4 schema = await JsonSchema4.FromTypeAsync<t>();
        return schema.ToJson();
    }
    catch (Exception ex)
    {
        Logger.WriteToLogFile(ex.ToString(), "exception");
        return "";
    }
}

[PROBLEM] Now the main problem is that variable t is evaluated at runtime, thus, JsonSchema4.FromTypeAsync<t>() throws the error 't' is a variable but is used like a type when trying to build compile time

Whoever used JsonSchema4 will understand what I'm trying to achieve here. Instead of creating a generate function for each of my models, or make a switch/if-else logic,

[QUESTION] How to make it receive the model name as a string parameter, and convert the string-model-name to model-type and pass it to jSonSchema4 method.





Aucun commentaire:

Enregistrer un commentaire