使用 row.Field<T>(col) 和基于 row/col 索引获取单元格值之间的区别

Difference between get cell value using row.Field<T>(col) and based on row/col index

我是 c# 的新手,我有这个运行良好的脚本

foreach(DataColumn col in dataTab.Columns){
 foreach(DataRow row in dataTab.Rows){
  row.Field<decimal>(col).ToString(CultureInfo.InvariantCulture); }}

我必须使用 ToString(CultureInfo.InvariantCulture) 才能读取小数点分隔符。无论如何,当我更改此代码时,在 rows/columns 索引上循环并放置 dataTab[rowIndx][colIndx].ToString(CultureInfo.InvariantCulture) 我在 ToString 方法中收到错误消息:

no overload for method tostring takes 1 argument

1。我该如何解决这个错误?

  1. 为什么第一次成功了,第二次不行,这两种方法有什么区别?

row.Field<T> 是一个通用方法,你会得到一些强类型的东西(在你的情况下是 decimal),它有自己的 ToString() 实现,包括采用 CultureInfo作为参数。

然而,第二种使用索引的方法只会返回一个 object。这就是您收到错误的原因,因为 object.ToString() 确实没有采用 1 个参数的重载。

row.Field<decimal>(col).ToString(CultureInfo.InvariantCulture);

此行显示为十进制。 Decimaltype 有一个 ToString 重载接受 Cultureinfo。

dataTab[rowIndx][colIndx]

此行显示为对象。对象没有 有接受 Cultureinfo 的 ToString 重载。

其他答案已经涵盖问题 #2

why did it work in the first time and not in the second, what is the difference between the two methods?

这是问题 #1 的答案

How can I fix this error?

您可以使用 Convert.ToString Method (Object, IFormatProvider):

Convert.ToString(dataTab[rowIndx][colIndx], CultureInfo.InvariantCulture)