将Dictionary作为参数传递给函数

时间:2014-04-24 17:42:46

标签: asp.net vb.net dictionary

我创建了我的数据字典:

Dim data As New Dictionary(Of String, String)
data.Add("customer", "TEST")
data.Add("secretKeyId", "2222222222222")
data.Add("secretKey", "333333333333333")

我有以下功能:

 Public Shared Function Create(ByVal data As Dictionary(Of String, Object)) As [String]
    ' Serializes the body into JSON using the fastJSON library.
    Dim json As String = Newtonsoft.Json.JsonConvert.SerializeObject(data)
    Dim body As Byte() = Encoding.UTF8.GetBytes(json) ....

如何调用Create函数并将DATA与我输入的所有键和值一起传递给此函数?

我尝试过:create(data.all)create(data)但它无效。

1 个答案:

答案 0 :(得分:0)

您正在尝试将不兼容的数据类型传递给您的方法:在您的调用方法中,您的字典的类型为string, string,您的函数等待类型为string, object的字典。你有两个解决方案:

  • 将主要部分中字典的签名更改为Dim data As New Dictionary(Of String, Object)
  • 或将签名更改为方法的字典参数ByVal data As Dictionary(Of String, String)

可能的解决方案如下:

Public Shared Function Create(ByVal data As Dictionary(Of String, String)) As [String]
    ' Serializes the body into JSON using the fastJSON library.
    Dim json As String = Newtonsoft.Json.JsonConvert.SerializeObject(data)
    return json
end function

电话:

Dim data As New Dictionary(Of String, String)
data.Add("customer", "TEST")
data.Add("secretKeyId", "2222222222222")
data.Add("secretKey", "333333333333333")
Dim dataAsJson = Create(data)
Console.WriteLine(dataAsJson)

输出:

{"customer":"TEST","secretKeyId":"2222222222222","secretKey":"333333333333333"}

在这种情况下,这也可以正常工作并创建与上面相同的结果:

Public Shared Function Create(ByVal data As Dictionary(Of String, Object)) As [String]
    ' Serializes the body into JSON using the fastJSON library.
    Dim json As String = Newtonsoft.Json.JsonConvert.SerializeObject(data)
    return json
end function

Dim data As New Dictionary(Of String, Object)
data.Add("customer", "TEST")
data.Add("secretKeyId", "2222222222222")
data.Add("secretKey", "333333333333333")
Dim dataAsJson = Create(data)
Console.WriteLine(dataAsJson)