DataTable.Compute的“指定的强制转换无效”?

时间:2011-12-07 14:20:53

标签: c# casting datatable

我这里有这个代码:

decimal dec = (decimal)MyDataTable.Compute("Min(Rooms)", string.Empty);

它总是告诉我指定的演员表无效。我如何检查Compute是否会在运行时成功完成?

谢谢:)

2 个答案:

答案 0 :(得分:5)

试试这个

object dec = MyDataTable.Compute("Min(Rooms)", string.Empty);
decimal d;
bool result = Decimal.TryParse(dec.ToString(), out d);

如果resulttrue则表示解析成功

答案 1 :(得分:2)

尝试使用Decimal.TryParse()看看这是否对您有所帮助。 Here is the msdn 这应该有效:

        var s = "123.34";
        decimal d;

        bool isDec = Decimal.TryParse(s, out d);

        if (isDec)
            Console.WriteLine("It was a decimal: " + d);
        else
            Console.WriteLine("Not a decimal!");

        Console.WriteLine(isDec);
        Console.ReadLine();

您需要两个参数的原因是第一个参数是字符串格式的十进制表示。如果TryParse成功,结果将存储在d中(在上面的示例中)。在上面的示例中,isDec打印true