C# - 通过 JsonSchema4.FromTypeAsync 使用反射

C# - Using reflection with JsonSchema4.FromTypeAsync

[简介] 我知道到处都有关于泛型和反射的无数 QA,但它对我来说变成了一个黑洞,而且我读得越多,我就越迷失!!

我需要做的很简单,我很惊讶以前没有解决它。

[SAMPLE] 考虑以下代码片段:

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 "";
    }
}

[问题] 现在的主要问题是变量 truntime,因此,JsonSchema4.FromTypeAsync<t>() 在尝试构建 compile time

时抛出错误 't' is a variable but is used like a type

任何使用过 JsonSchema4 的人都会理解我在这里想要实现的目标。 而不是为我的每个模型创建一个生成函数,或者创建一个 switch/if-else 逻辑,

[问题] 如何让它接收模型名称作为 字符串参数 ,并将字符串模型名称转换为模型类型并将其传递给 jSonSchema4 方法。

这里的问题是,正如你所说,t 被评估为运行时。

我也 运行 解决了这个问题,并通过创建一个 MethodInfo 我想调用的方法解决了这个问题,在你的例子中 JsonSchema4.FromTypeAsync<t>().

所以基本上这可能会解决问题:

    var methodInfo = typeof(JsonSchema4).GetMethod("FromTypeAsync", new Type[] { }); //Get the "normal method info", the overload without parameters
    var methodInfoWithType = methodInfo.MakeGenericMethod(t); //now you have a method with your desired parameter t as TypeParameter
    Task<JsonSchema4> task = methodInfoWithType.Invoke(null, null) as Task<JsonSchema4>; //now you can cast the result from invoke as Task to keep the Async-Await functionality
    var schema = await task;
    return schema.ToJson();