c# - 使用变量作为类型

标签 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
    }

提前致谢

最佳答案

您将无法使用常规语法 ( CreateTable<model> ) 将变量用作通用类型。不知道是什么CreateTable是的,你有两个选择:

  1. 而不是制作 CreateTable一个泛型方法,让它以类型作为参数:

    public static void CreateTable(Type modelType)
    {
    }
    
  2. 使用反射动态调用使用所需类型的泛型方法:

    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
    }
    

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

关于c# - 使用变量作为类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35804075/

相关文章:

c# - .Net 的 LINQ 中存在错误,或者我遗漏了什么?

c# - 任何有助于找到多个字符串的最长公共(public)起始子字符串的框架函数?

c# - ParallaxView 在 4 月更新后不起作用

c# - System.Uri.ToString() 取消转义 uri 编码的查询字符串。如何阻止它?

c# - 如何将 ListBox 绑定(bind)到 XML 文件中的对象列表?

c# - .NET 语句的表达式

c# - Caliburn - 子 ViewModel 的 PropertyChanged

c# - 将数据集导出到 asp.net c# 中的 excel 表

c# - .NET WinForms 应用程序中的异常什么时候可以被吃掉而不被捕获或冒泡到 Windows 异常?

c# - 垃圾收集是否在 GC.Collect() 之后立即运行?