我在代码中遇到问题,它告诉system.int32
无法转换为system.double
,这是我的代码
我有一个包含4个字符串变量和2个整数变量的对象。
public class MyObject
{
public int id;
public string name1;
public string name2;
public string name3;
public string name4;
public int id2;
}
/*Converts DataTable To List*/
public static List<TSource> ToList<TSource>(this DataTable dataTable) where TSource : new()
{
var dataList = new List<TSource>();
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;
var objFieldNames = (from PropertyInfo aProp in typeof(TSource).GetProperties(flags)
select new { Name = aProp.Name, Type = Nullable.GetUnderlyingType(aProp.PropertyType) ?? aProp.PropertyType }).ToList();
var dataTblFieldNames = (from DataColumn aHeader in dataTable.Columns
select new { Name = aHeader.ColumnName, Type = aHeader.DataType }).ToList();
var commonFields = objFieldNames.Intersect(dataTblFieldNames).ToList();
foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
{
var aTSource = new TSource();
foreach (var aField in objFieldNames)
{
PropertyInfo propertyInfos = aTSource.GetType().GetProperty(aField.Name);
propertyInfos.SetValue(aTSource, dataRow[aField.Name], null);
}
dataList.Add(aTSource);
}
return dataList;
}
在我的objectfieldname
变量中,我获取了具有正确数据类型的所有变量,但在dataTblFieldNames
变量中,它将int转换为double,因此我在propertyinfos
中遇到问题foreach loop
1}}它的说法
'System.Double'类型的对象无法转换为'System.Int32'类型。
有人帮我解决这个问题吗?
答案 0 :(得分:3)
您可以使用Convert.ChangeType
method:
Convert.ChangeType(dataRow[aField.Name], propertyInfos.PropertyType)
它会尝试一些数字转换(例如从double
到int
的转换,二进制表示从浮点到整数的变化(2&#39;补码))和一些格式化/解析来自string
。
答案 1 :(得分:1)
在分配值之前,您已找到属性类型,并且还必须将值转换为所需类型,因为您无法直接将double类型赋值为int类型。
if (propertyInfos.PropertyType == typeof(int))
{
propertyInfos.SetValue(aTSource, Convert.ToInt32(dataRow[aField.Name]), null);
}
答案 2 :(得分:0)
您的输入dataRow[aField.Name]
属于System.Double
类型,而您要分配的字段属于System.Int32
类型。但Visual Studio已经如此响亮而清晰地告诉你了。
我无法告诉你该做什么,因为我不知道你想做什么。通过施法来截断双重?向上或向下舍入?也许这是一个错误的领域?我们不知道。你决定。
考虑到你不太可能想出上面的代码并且仍然不理解错误这一事实,也许这是一个好主意,要么获得一个完整的睡眠和一杯好咖啡或者问一个最初写这个代码的人