[英]System.InvalidCastException in C# console
当我执行以下代码时,出现错误提示。
System.InvalidCastException: Specified cast is not valid.
at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
at ProbabilityFunctions.Program.Main(String[] args) in C:\Users\....:line 38Press any key to continue . . .
我要在这段代码中尝试做的是,我正在从一个表中检索数据并将其存储到另一个表中。 我将此表作为参数传递给分类器,以进行进一步的操作。 请告诉我错误。 height,uname的数据类型是varchar ...其他是int ...
using System;
using System.Data;
using MySql.Data.MySqlClient;
namespace ProbabilityFunctions
{
public class Program
{
static void Main(string[] args)
{
try
{
String con = "SERVER=localhost;DATABASE=sample;UID=root;password=password";
MySqlConnection conn = new MySqlConnection(con);
String s = "select * from cart";
MySqlCommand cmd = conn.CreateCommand();
MySqlCommand cmd2 = conn.CreateCommand();
cmd2.CommandText = "select count(*) from cart";
conn.Open();
int z = Convert.ToInt32(cmd2.ExecuteScalar());
conn.Close();
MySqlDataAdapter dat = new MySqlDataAdapter(s, conn);
DataTable tbl = new DataTable();
dat.Fill(tbl);
cmd.CommandText = s;
DataTable table = new DataTable();
table.Columns.Add("name");
table.Columns.Add("Height", typeof(double));
table.Columns.Add("cost", typeof(double));
table.Columns.Add("FootSize", typeof(double));
for (int i = 0; i < z; i++)
{
DataRow row = tbl.Rows[i];
Double height = row.Field<Double>("height");
Double fsize = row.Field<Double>("fsize");
Double cost = row.Field<Double>("cost");
String uname = row.Field<String>("uname");
table.Rows.Add(uname, height, cost, fsize);
}
Classifier classifier = new Classifier();
classifier.TrainClassifier(table);
Console.WriteLine(classifier.Classify(new double[] { 4, 150, 12 }));
Console.Read();
}
catch (Exception ex)
{
Console.Write(ex.ToString());
}
}
}
}
这很可能发生在以下这些行之一:
Double height = row.Field<Double>("height");
Double fsize = row.Field<Double>("fsize");
Double cost = row.Field<Double>("cost");
如果基础字段类型不能直接转换为double,则将收到此异常。 从Field<T>
的文档中 ,在以下情况下会引发InvalidCastException:
基础列的值类型不能转换为通用参数T指定的类型。
给定堆栈跟踪,则基础表中的“ height”列实际上不是数字,并且不能转换为双精度。 例如,如果将其作为字符串存储在输入数据集中,则必须提取一个字符串,然后转换为双精度型。
现在很清楚。 您不能将装箱的int
拆箱为double
或任何其他类型。 仅允许的可能类型是int
和Nullable<int>
。
将Field获取为int并将其转换为double,然后应该可以工作
double height = (double)row.Field<int>("height");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.