0

我有一个对象数组,我想将它传递给一个只接受DOUBLENULL或的STRING方法DATETIME。因此,当我尝试传入该值时,它会给出一个错误,指出我不能传入任何任意对象,并且必须将其解析为、DOUBLENULL首先。STRINGDATETIME

foreach (var currRow in dataSet.Tables[0].Rows)
{
    var tuple = Com.Tibco.As.Space.Tuple.Create();

    //here is where i loop through the object array
    for (int i = 0; i < currRow.Values.Length; i++)
    {
        //here is where i try to pass it to the method (which doesn't accept it)
        tuple.Put(dataSet.Tables[0].ColumnNames[i], currRow.Values[i]);
    }

    inSpace_.Put(tuple);
}

这是对象数组的样子

简而言之,我需要一种方法来解析每个对象并将其转换为适当的对象,然后将其放入元组中。

编辑

这是我试图做的,但没有奏效:

foreach (var currRow in dataSet.Tables[0].Rows)
{
    var tuple = Com.Tibco.As.Space.Tuple.Create();

    for (int i = 0; i < currRow.Values.Length; i++)
    {
        if (currRow.Values[i] != null)
        {
            if (dataSet.Tables[0].ColumnNames[i].GetType().IsEquivalentTo(typeof(DateTime)))
            {
                DateTime value = DateTime.Parse(dataSet.Tables[0].ColumnNames[i].ToString());
                tuple.Put(dataSet.Tables[0].ColumnNames[i], value);
            }
            else if (dataSet.Tables[0].ColumnNames[i].GetType().IsEquivalentTo(typeof(Double)))
            {
                Double value = Convert.ToDouble(dataSet.Tables[0].ColumnNames[i]);
                tuple.Put(dataSet.Tables[0].ColumnNames[i], value);
            }
            else
            {
                string value = dataSet.Tables[0].ColumnNames[i].ToString();
                tuple.Put(dataSet.Tables[0].ColumnNames[i], value);
            }
        }
    }
    inSpace_.Put(tuple);
}
4

2 回答 2

1
foreach (var currRow in dataSet.Tables[0].Rows)
{
    var tuple = Com.Tibco.As.Space.Tuple.Create();

    for (int i = 0; i < currRow.Values.Length; i++)
    {
        var obj = dataSet.Tables[0].ColumnNames[i], currRow.Values[i];
        var value = null;
        value = obj as double;
        if (!validObject(value)) value as string;
        if (!validObject(value)) value as DateTime;
        tuple.Put(dataSet.Tables[0].ColumnNames[i], value);
    }

    inSpace_.Put(tuple);
}

bool validObject(object obj) { return (null != obj); }

更新,根据您的编辑,我会改用开关类型:

for (int i = 0; i < currRow.Values.Length; i++)
{
    var type = obj.GetType();
    var obj = dataSet.Tables[0].ColumnNames[i], currRow.Values[i];
    var value = null;
    switch (type)
    {
        case DateTime:
            value = DateTime.Parse(obj);
            break;
        case double:
            value = Convert.ToDouble(obj);
            break;
        case string:
            value = Convert.ToString(obj);
            break;
    }
    tuple.Put(dataSet.Tables[0].ColumnNames[i], value);
}
于 2013-03-07T19:07:08.033 回答
0

如果您在编译时知道类型,请使用Convert.ToDouble,Convert.ToInt32等。如果您不知道,请使用Convert.ChangeType.

于 2013-03-07T19:07:06.210 回答