从Dictionary获取,它是Object的实例

时间:2019-07-02 06:29:35

标签: c# .net list object

我正在使用一个返回对象的函数,并且该对象是一个列表。 我无法使用索引来获取属性。

我的代码:

获取对象

Object myObject = x.ImportDataFromX(Int32.Parse(txtX.Text),dataGViewX.Rows[i].Cells[6].Value.ToString());

使用索引:

dataGViewX.Rows[i].Cells[5].Value = myObject[5]; //ERROR

功能:

Public Function ImportDataFromX(ByVal ClientID As Integer, ByVal BarcodeID As String) As Object
        Dim DrByBarcode As DataTable = GetTable("select MainInfo,FromNumber,ToNumber,FromDate,ToDate,BeurDate,Field1,Field2,Field3 from BoxsInfo inner join TblBoxsPreIndex on BoxsInfoID=[BoxsInfo].id where TblBoxsPreIndex.[ClientId]=" & ClientID & " and [FormId]=-5000 and TblBoxsPreIndex.BarcodeID='" & BarcodeID & "'")

        Select Case DrByBarcode.Rows.Count
            Case 0
                Return "can't find  record to barcode: " & BarcodeID
            Case 1
                Dim Dr As New Dictionary(Of String, String)
                Dr.Add("MainInfo", IIf(IsDBNull(DrByBarcode.Rows(0).Item("MainInfo")), "", DrByBarcode.Rows(0).Item("MainInfo")))
                Dr.Add("FromNumber", IIf(IsDBNull(DrByBarcode.Rows(0).Item("FromNumber")), "", DrByBarcode.Rows(0).Item("FromNumber")))
                Dr.Add("ToNumber", IIf(IsDBNull(DrByBarcode.Rows(0).Item("ToNumber")), "", DrByBarcode.Rows(0).Item("ToNumber")))
                Dr.Add("FromDate", IIf(IsDBNull(DrByBarcode.Rows(0).Item("FromDate")), "", DrByBarcode.Rows(0).Item("FromDate")))
                Dr.Add("ToDate", IIf(IsDBNull(DrByBarcode.Rows(0).Item("ToDate")), "", DrByBarcode.Rows(0).Item("ToDate")))
                Dr.Add("BeurDate", IIf(IsDBNull(DrByBarcode.Rows(0).Item("BeurDate")), "", DrByBarcode.Rows(0).Item("BeurDate")))
                Dr.Add("Field1", IIf(IsDBNull(DrByBarcode.Rows(0).Item("Field1")), "", DrByBarcode.Rows(0).Item("Field1")))
                Dr.Add("Field2", IIf(IsDBNull(DrByBarcode.Rows(0).Item("Field2")), "", DrByBarcode.Rows(0).Item("Field2")))
                Dr.Add("Field3", IIf(IsDBNull(DrByBarcode.Rows(0).Item("Field3")), "", DrByBarcode.Rows(0).Item("Field3")))


                Return Dr

            Case > 1
                Return " barcode" & BarcodeID & "duplicate"
        End Select
    End Function

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以通过将object强制转换为Dictionary来获得价值:

dataGViewX.Rows[i].Cells[5].Value = ((Dictionary<string, string>)myObject)["BeurDate"];

dataGViewX.Rows[i].Cells[5].Value = (myObject as Dictionary<string, string>)["BeurDate"];

如果要按索引获取值,可以使用ElementAt

dataGViewX.Rows[i].Cells[5].Value = ((Dictionary<string, string>)myObject).Values.ElementAt(5);

但是请记住,不能保证Dictionary的顺序。因此,请使用您的Dictionary键而不是使用值索引。或者,您可以使用 OrderedDictionary