[英]Is it possible to define a column type in DataTable at run time?
I would like to create a DataTable but I don't know the types of columns at compile time. 我想创建一个DataTable,但是在编译时我不知道列的类型。 Therefore, I would like the columns types to be decided at run-time. 因此,我希望在运行时确定列类型。
WHAT I'VE TRIED: 我尝试过的内容:
First, I get some data from Excel: 首先,我从Excel获得一些数据:
Type tempCheck = (dynamic)(xlRange.Cells[1, currentColumnsCount] as Excel.Range).Value2.GetType();
Then I try to use the type to create a column. 然后,我尝试使用该类型来创建列。
myDataTable.Columns.Add(columnName, typeof(tempCheck.GetType());
I get the error: 我得到错误:
The type or namespace name 'tempCheck' could not be found (are you missing a using directive or an assembly reference?) 找不到类型或名称空间名称“ tempCheck”(您是否缺少using指令或程序集引用?)
tempCheck
is already a type, so you don't need the typeof
: tempCheck
已经是一种类型,因此您不需要typeof
:
myDataTable.Columns.Add(columnName, tempCheck);
typeof
is an operator that is used to get an instance of System.Type
from a type name, and this is done at compile time. typeof
是一个运算符,用于从类型名称获取System.Type
的实例,该操作在编译时完成。
The error "The type or namespace name 'tempCheck' could not be found" is coming because since typeof
is looking for a compile-time type, it's literally looking for a type called tempCheck
, like a class or delegate, etc. 出现错误“无法找到类型或名称空间名称'tempCheck'”,这是因为由于typeof
在寻找编译时类型,因此实际上是在寻找名为tempCheck
的类型,例如类或委托等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.