是否可以在运行时在DataTable中定义一个列类型?
Is it possible to define a column type in DataTable at run time?
我想创建一个数据表,但我不知道编译时列的类型。因此,我希望在 运行 时间确定列类型。
我尝试了什么:
首先,我从 Excel 获取了一些数据:
Type tempCheck = (dynamic)(xlRange.Cells[1, currentColumnsCount] as Excel.Range).Value2.GetType();
然后我尝试使用类型创建列。
myDataTable.Columns.Add(columnName, typeof(tempCheck.GetType());
我收到错误:
The type or namespace name 'tempCheck' could not be found (are you
missing a using directive or an assembly reference?)
tempCheck
已经是一种类型,因此您不需要 typeof
:
myDataTable.Columns.Add(columnName, tempCheck);
typeof
是一个运算符,用于从类型名称中获取 System.Type
的实例,这是在编译时完成的。
出现错误 "The type or namespace name 'tempCheck' could not be found" 是因为 typeof
正在查找编译时类型,它实际上是在查找名为 tempCheck
的类型,例如 class或委托等
我想创建一个数据表,但我不知道编译时列的类型。因此,我希望在 运行 时间确定列类型。
我尝试了什么:
首先,我从 Excel 获取了一些数据:
Type tempCheck = (dynamic)(xlRange.Cells[1, currentColumnsCount] as Excel.Range).Value2.GetType();
然后我尝试使用类型创建列。
myDataTable.Columns.Add(columnName, typeof(tempCheck.GetType());
我收到错误:
The type or namespace name 'tempCheck' could not be found (are you missing a using directive or an assembly reference?)
tempCheck
已经是一种类型,因此您不需要 typeof
:
myDataTable.Columns.Add(columnName, tempCheck);
typeof
是一个运算符,用于从类型名称中获取 System.Type
的实例,这是在编译时完成的。
出现错误 "The type or namespace name 'tempCheck' could not be found" 是因为 typeof
正在查找编译时类型,它实际上是在查找名为 tempCheck
的类型,例如 class或委托等