简体   繁体   中英

VB.Net Why does my dictionary need to be explicitly declared in order to use select?

Using VB.Net with MVC5.

I have a dictionary:

Dim Filter as New Dictionary(Of String, Object)

' the key's value is another dictionary
Filter.Add("customParams", New Dictionary(Of String, String) From {{"k1","v1"}, {"k2","v2"}, {"k3","v3"}})

and I am trying to convert the Filter("customParams") value, which is a Dictionary(Of String, String), to a delimited string, "k1=v1, k2=v2, k3=v3"

This doesn't work:

Dim kvString As String = String.Join(", ", Filter("customParams").Select(Function(x) x.Key & "=" + x.Value).ToArray())

I get this exception:

Public member 'Select' on type 'Dictionary(Of String,String)' not found.

But if I explicitly declare a new variable for the Dictionary(Of String,String) and use that instead of Filter("customParams") then this works:

Dim customParams As Dictionary(Of String, String) = Filter("customParams")
Dim kvString As String = String.Join(", ", customParams.Select(Function(x) x.Key & "=" + x.Value).ToArray())

Why doesn't it work the other way? The exception itself says that it's working with a Dictionary(Of String, String)

By default, VB.Net allows late binding ( OPTION STRICT OFF ). Late binding is the equivalent of dynamic in C# and means the runtime looks up the method to call by name and the compiler does not type checking or validation. Only public members can be accessed by late binding, so extension (friend) methods such as Select are not available. This is automatic for object variables in VB.Net. customParams has a (non- object ) assigned type and thus uses early binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM