运算符+ =不能应用于类型为object和object的操作数 [英] operator += cannot be applied to operands of type object and object
本文介绍了运算符+ =不能应用于类型为object和object的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
亲爱的所有
我对此编码有点问题
Dear all
i have problem with this bit of coding
dr["DataColumn1"] += dtshort.Rows[0][0];
当我将值传递给dtshort.Rows [0] [0] = 1时,它将很好地存储dr ["DataColumn1"],但是我的问题是当我使用循环时,我想向dr ["DataColumn1"]连续添加值br/>
如何做到这一点,...
when i pass value to dtshort.Rows[0][0]=1, it ll store dr["DataColumn1"] it fine but my prob is when i am using loop i want continuously add value to dr["DataColumn1"]
How to do this,...
推荐答案
1.实际上,使用DataReader
从数据源获取的值是boxed
对象,它们应unboxed
为其原始类型,如下例所示:
1. The values get from the data source by usingDataReader
are in factboxed
objects and they should beunboxed
to their original types like in the next example:
string name = (string)dr["DataColumn1"];
double number = (double)dr["DataColumn2"];
2.有关boxing
和unboxing
的更多详细信息,请参见MSDN: http://msdn.microsoft .com/en-us/library/yz2be5wk.aspx [
2.For more details about boxing
and unboxing
see in MSDN:http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx[^]
dr [" DataColumn1]可以处理不同类型的数据,以将其类型设置为object(毕竟所有都是对象) .
但是对象不能实现+ =的运算符,因为这是一个普通类型,并且+ =运算符对于不同的实际类型(想象中的1 + 1和``1''+''1'')可能会大不相同...
您可以做的是将dr ["DataColumn1"]转换为它的预期类型,然后应用+ =运算符:
dr["DataColumn1"] can handle different types of data, to do that its type set to object (after all everything is an object).
However object do not implement the operator of += as this is a common type and += operator can be very different for different actual types (imagine 1+1 and ''1''+''1'')...
What you can do is convert dr["DataColumn1"] to it''s expected type and than apply += operator:
int n = Convert.ToInt32(dr["DataColumn1"]);
dr["DataColumn1"] = n + Convert.ToInt32(dtshort.Rows[0][0]);
这篇关于运算符+ =不能应用于类型为object和object的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文