C# 将对象强制转换为DataColumn的类型

C# 将对象强制转换为DataColumn的类型,c#,casting,datatable,C#,Casting,Datatable,我正在广泛使用字典来解耦一些(高度耦合的)代码。以下是我的问题的相关内容: //Output table System.Data.DataTable dtOutput = new System.Data.DataTable(); dtOutput.Columns.Add("Ticket", typeof(string)); dtOutput.Columns.Add("Transit", typeof(string)); dtOutput.Columns.Add("City", typeof(st

我正在广泛使用字典来解耦一些(高度耦合的)代码。以下是我的问题的相关内容:

//Output table
System.Data.DataTable dtOutput = new System.Data.DataTable();
dtOutput.Columns.Add("Ticket", typeof(string));
dtOutput.Columns.Add("Transit", typeof(string));
dtOutput.Columns.Add("City", typeof(string));
dtOutput.Columns.Add("Province", typeof(string));
dtOutput.Columns.Add("Outage Start Time", typeof(DateTime));
dtOutput.Columns.Add("Outage End Time", typeof(DateTime));
dtOutput.Columns.Add("Priority", typeof(string));
dtOutput.Columns.Add("Business Impact", typeof(TimeSpan));
dtOutput.Columns.Add("Time To Repair (mins)", typeof(Double));
dtOutput.Columns.Add("Summary", typeof(string));

Dictionary<string, int> outputColumnsLegend = new Dictionary<string, int>();
foreach (DataColumn col in dtOutput.Columns)
{
    outputColumnsLegend.Add(col.ColumnName, dtOutput.Columns.IndexOf(col) + 1);
}

Dictionary<string, Variable> outputVariable = new Dictionary<string, Variable>()
{
    {"Ticket", new Variable()},
    {"Transit", new Variable()},
    {"City", new Variable()},
    {"Province", new Variable()},
    {"Outage Start Time", new Variable()},
    {"Outage End Time", new Variable()},
    {"Priority", new Variable()},
    {"Business Impact", new Variable()},
    {"Time To Repair (mins)", new Variable()},
    {"Summary", new Variable()}
};
现在,要创建我尝试使用的输出表:

DataRow dataRow = dtOutput.NewRow();
foreach (DataColumn col in dtOutput.Columns)
{
    dataRow[outputColumnsLegend[col.ColumnName]] = (col.DataType)outputVariable[col.ColumnName].Value;
}
但是,col.DataType中对col的引用会导致此错误:

The type or namespace 'col' could not be found (are you missing a using directive or an assembly reference?)
我不知道我为什么抛出这个错误或者如何修复它。另外,我不确定col.DataType是否应该改为col.GetType(假设这可以实现)

任何建议都将不胜感激


注意。

此代码没有净结果。 因为DataTable将数据存储为对象(这就是为什么在从中获取数据时必须强制转换),并且由于Variable()类持有对象,所以实际上再多的强制转换都不会做任何有用的工作

基本上,您正在取消装箱,然后立即在同一行上重新装箱数据,即使强制转换已成功

如果您希望在运行时保留类型以避免这种情况(这似乎是您正在尝试的),那么您需要将变量类设置为泛型类,如下所示:

public class Variable<T>
{
   public T Value {get; set;}
}
公共类变量
{
公共T值{get;set;}
}
然后,您将实例化特定类型的变量,例如:

Variable<int> someInt;
Variable<string> someString;
etc.
变量someInt;
变量字符串;
等

然而,即使这样做,在您将其放入数据表时,您仍然会将其作为对象装箱,因此这是一个徒劳的练习。

您想用该石膏做什么?该转换将不起作用,也不会产生任何净结果。是否正在查找typeof(object)?
outputVariable[col.ColumnName]。Value
返回一个对象。我只是假设它需要转换为特定列的适当类型。是的,它的错误也在我的末尾。无论我使用typeof(col)还是typeof(outputVariable[col.ColumnName].Value),typeof(object)都会抛出相同的错误
Variable<int> someInt;
Variable<string> someString;
etc.