我想创建一个数据表,但我不知道编译时列的类型。因此,我希望在运行时确定列类型。
我尝试过的:
首先,我从 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 的实例,这是在编译时完成的。
错误“找不到类型或命名空间名称‘tempCheck’”是因为 typeof 正在寻找编译时类型,它实际上是在寻找名为 的类型tempCheck,如类或委托(delegate)等
