【问题标题】:Convert String Value to User Defined Type将字符串值转换为用户定义的类型
【发布时间】:2013-05-23 06:47:39
【问题描述】:

您好,我想将字符串值转换为 DataType,以便我可以使用它。首先我想描述一下我的问题。

1:我输入了名为 Files
的数据集 2:此数据集包含 6 个数据表
3:数据表名称为(File01File02File03File04File05 , 文件06)
4:现在我想动态检查要调用哪个 DataTable 并使用 Reflection 创建该类的实例。

string dataTableName = filename + "DataTable"; //This will generate File01DataTable,File02DataTable...,File06DataTable
Type dataTableType = typeof ( Files.File01DataTable ).Assembly.GetType( dataTableName );

5:现在创建该 DataTable 的实例。这里的 tDS 是 TypedDataSet Files Instance

dataTableType dt = ( dataTableType )tDS.Tables[filename];

6:但上述方法不起作用。当我尝试返回类型时,它返回 null 而不是那个类。有人可以指导我。
在此先感谢

编辑: 好吧,谢谢ronnie 因为你解决了我 50% 的问题。现在,当我在这里输入类型是实例化对象的另一种情况。

string dataTableName = filename + "DataTable";// It Generate File01DataTable and so on till File06DataTable.

现在当我想在运行时实例化对象时,我无法告诉它

File01DataTable dt = (File01DataTable) tDS.Table[filename];

相反,我需要通用对象,它应该在运行时决定实例化哪个对象,例如 File02DataTable 或 File05DataTable。那么我该如何克服这个问题呢?

【问题讨论】:

  • 为什么要使用强类型松散类型的数据集?
  • 因为这是我的需要...

标签: c# dataset strongly-typed-dataset


【解决方案1】:

你的类是嵌套的吗?如果是这样,您将需要在类之间添加“+”字符。此外,需要一个完全引用的命名空间来返回类型。

namespace SO
{
    class Program
    {
        static void Main(string[] args)
        {
            string dataTableName = "SO.Files+File01DataTable";
            Type dataTableType = typeof(Files.File01DataTable).Assembly.GetType(dataTableName);
            Files.File01DataTable dt = (Files.File01DataTable)Activator.CreateInstance(dataTableType);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2011-12-21
    • 2020-03-17
    • 2019-11-22
    相关资源
    最近更新 更多