提问人:nactyx 提问时间:8/25/2023 最后编辑:wohlstadnactyx 更新时间:8/26/2023 访问量:53
错误 CS0021:无法将带有 [] 的索引应用于“object”类型的表达式
error CS0021: Cannot apply indexing with [] to an expression of type 'object'
问:
我的代码:
foreach(var row in dt_test.Rows)
{
if (DateTime.ParseExact(row["TestDate"].ToString(),"dd.MM.yyyy",System.Globalization.CultureInfo.InvariantCulture) > DateTime.ParseExact("01.11.2019","dd.MM.yyyy",System.Globalization.CultureInfo.InvariantCulture))
{
dt_test.Rows.Remove(row);
}
}
dt_test.AcceptChanges();
错误:
错误 CS0021:无法将带有 [] 的索引应用于“object”类型的表达式
我该如何解决?
我试图重做 linq 查询,但没有任何效果。
答:
1赞
Tim Schmelter
8/25/2023
#1
出现此错误的原因是您在 和 not 中使用了 。如果使用后者,则可以自动将对象强制转换为 。从 返回的 DataRowCollection
是旧的,不实现,而只是非泛型 。这就是获取对象的原因。var
foreach
DataRow
foreach
DataRow
DataTable.Rows
IEnumerable<DataRow>
ICollection
foreach
foreach(DataRow row in dt_test.Rows)
{
// now you can use the methods of DataRow like the indexer
}
除此之外,您不能在枚举表时从表中删除行。您将收到一个异常“集合已修改;枚举操作可能无法执行”。但是您可以先填写删除列表:foreach
List<DataRow> removeList = new();
foreach(DataRow row in dt_test.Rows)
{
If(condition)
{
removeList.Add(row);
}
}
removeList.ForEach(dt_test.Rows.Remove);
评论
0赞
nactyx
8/26/2023
蒂姆,谢谢你!现在它可以正常工作
-1赞
Ivan Stulskij
8/26/2023
#2
使用 var 时,编译器将行变量解析为对象。当您将光标光标放在行上时,您可以看到它。您不应将其确定为 var,而应将其确定为 DataRow
评论
var
DataRow
var
DataRow
var
row