使用变量作为类型

Mak*_*iek 8 c#

是否可以使这些代码有效?:

    private List<Type> Models = new List<Type>()
    {
        typeof(LineModel), typeof(LineDirectionModel), typeof(BusStopTimeModel), typeof(BusStopNameModel)
    };

    foreach (Type model in Models) // in code of my method
    {
        Connection.CreateTable<model>(); // error: 'model' is a variable but is used like a type
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢

Ari*_*edi 8

您将无法使用常规语法 ( CreateTable<model>) 将变量用作泛型类型。在不知道是什么的CreateTable情况下,您有两种选择:

  1. 不要创建CreateTable泛型方法,而是将类型作为参数:

    public static void CreateTable(Type modelType)
    {
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用 Reflection 使用所需类型动态调用泛型方法:

    var methodInfo = typeof (Connection).GetMethod("CreateTable");
    foreach (Type model in Models)
    {
        var genericMethod = methodInfo.MakeGenericMethod(model);
        genericMethod.Invoke(null, null); // If the method is static OR
        // genericMethod.Invoke(instanceOfConnection, null); if it's not static
    }
    
    Run Code Online (Sandbox Code Playgroud)

请注意,反射方式会更慢,因为方法信息要到运行时才会解析。