2

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

//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()}
};

其中变量很简单:

public class Variable
{
    public object Value { get; set; }
}

现在,要创建我要使用的输出表:

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(假设这可以工作)。

任何建议表示赞赏。

问候。

4

1 回答 1

1

此代码没有最终结果。因为 DataTable 将数据存储为对象(这就是为什么在从中获取数据时必须进行转换),并且由于您的 Variable() 类包含一个对象,所以实际上再多的转换也不会做任何有用的工作。

基本上,您是在拆箱,然后立即在同一行上重新装箱数据,即使演员表已经生效。

如果您想在运行时保留类型以避免这种情况(这似乎是您可能正在尝试做的事情),那么您需要使您的变量类成为一个泛型类,如下所示:

public class Variable<T>
{
   public T Value {get; set;}
}

然后,您将实例化特定类型的变量,例如:

Variable<int> someInt;
Variable<string> someString;
etc.

然而,即使你这样做了,当你把它放到 DataTable 中时,你仍然会作为一个对象装箱,所以这是徒劳的练习。

于 2012-08-18T02:04:05.747 回答