【问题标题】:C# equivalent to VB's "System.Data.DataRow.Item"?C#相当于VB的\"System.Data.DataRow.Item\"?
【发布时间】:2022-08-22 23:38:31
【问题描述】:

我试图找到与 VB 的 \"System.Data.DataRow.Item\" 等效的东西,但我找不到。我正在将 VB 代码重写为 C#,而且我是 C# 的新手。菜鸟问题,可能。我想你们会有一些很好的见解。代码 sn-p 如下。我发现另一个堆栈溢出帖子有类似的问题,但答案对我没有帮助,所以我发布了这个。

这也是错误:Error CS1061 \'DataRow\' does not contain a definition for \'Item\' and no accessible extension method \'Item\' accepting a first argument of type \'DataRow\' could be found (are you missing a using directive or an assembly reference?)

...
// C# code                         
if (Reader.HasRows) // check that data exists
{
    var winshare = new DataTable();
    winshare.Load(Reader);
    foreach (DataRow row in winshare.Rows)
    {                                
        string path = row.Item[\"List_Item\"]; 
        path = path + @\"\\Out\";
        GlobalVariables.pwc = row.Item[\"Sublist_Id\"];
...
...
// VB code  
If Reader.HasRows Then // check that data exists
    Dim winshare As DataTable = New DataTable
    winshare.Load(Reader)
    For Each row As DataRow In winshare.Rows
        Dim path As String = CStr(row.Item(\"List_Item\"))
        path = path + \"\\Out\"
        pwc = CStr(row.Item(\"Sublist_Id\")) // Used to determine archive path also
...
  • 请尝试:row.Item[\"Sublist_Id\"]; 这是一个 C# 数组。 docs.microsoft.com/en-us/dotnet/api/…
  • @MarkusMeyer 它不是一个数组,它是一个索引器。但是,与 VB 一样,它使用与数组相同的访问权限。
  • 这回答了你的问题了吗? VB.Net to C# conversion errors
  • 抱歉,我实际上确实从括号中进行了更改(我将在原始帖子上进行编辑以避免更多混淆)但不幸的是,在使用索引器括号 [] @Craig 时我仍然遇到完全相同的错误
  • @MarkusMeyer我很抱歉,我实际上已经更改了索引括号。 (我在原始帖子中进行了更改以避免混淆)但是即使使用正确的索引括号,我仍然会遇到相同的错误。

标签: c# vb.net datarow


【解决方案1】:

VB 有默认属性,C# 有索引器。在 VB 中,您可以显式指定默认属性,例如

pwc = CStr(row.Item("Sublist_Id"))

或隐含地:

pwc = CStr(row("Sublist_Id"))

C# 索引器与隐式选项基本相同:

pwc = (string)row["Sublist_Id"];

不管是哪种语言,我都倾向于推荐一些 LINQ to DataSet:

pwc = row.Field(Of String)("Sublist_Id")
pwc = row.Field<string>("Sublist_Id");

【讨论】:

  • 虽然我在这里有你,但为什么我不再需要像 VB 中的 row.Item 而是只在 C# 中使用 row["Sublist_Id"] ?我对那个tbh有点困惑。 @user18387401
  • 我在回答中告诉过你。你读过它吗? C# 中没有 Item 属性,因为 C# 使用索引器。如果您不知道 C# 索引器是什么,请阅读有关该主题的文档。
  • 我直观地知道索引器是什么,但可能没有我想象的那么深。我会仔细阅读它们。
【解决方案2】:

在 C# 中,您需要使用方括号 [] 而不是 parens (),因为它们不以这种方式使用。

row["List_Item"].ToString();

Item 方法似乎在其他地方。

https://docs.microsoft.com/en-us/dotnet/api/system.data.datarow.item?view=net-6.0

【讨论】:

  • 不幸的是,使用正确的索引括号我仍然遇到同样的错误。
  • 该项目可能会作为对象返回,因此您需要将其转换为字符串,就像您在 VB 中所做的那样
  • 话虽这么说,我通常不会使用 .Item 而只是去 row["List_Item"].ToString() 少这样打字。
  • 原来(string)row["Sublist_Id"]; 是正确的方法。
  • 添加 .Item 时,它给了我红色的波浪线。
猜你喜欢
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
相关资源
最近更新 更多