How would you solve this? I want to return this collection:
Public Function GetShippingMethodsByCarrier(ByVal Carrier As ShippingCarrier) As 开发者_JAVA百科List(of ?)
Return Carrier.ShippingMethods.Select(Function(x) New With {.ID = x.ID, .Name = String.Format("{0} {1}", Carrier.Name, x.Description)})
End Function
Thanks!!
You can't return an anonymous type from a function like this because it has no name.
Since this is a public function is should have a well defined return type. Create a new class holding those two properties.
Its possible to return it if the return type is an inferred generic parameter, but that's not what you want here. This is useful for LINQ where an anonymous type essentially gets passed through from a parameter to the result type, but not useful for what you're doing.
You could also use a Tuple, but then you'd lose the property names. And it wouldn't be extensible since adding a new property would break caller code. So I wouldn't recommend that either.
The problem here is you're attempting to return an anonymous type in a strongly typed manner. This is just not possible in VB.Net (or C# for that matter). Anonymous types are meant to be anonymous and their names cannot be stated explicitly in code. The two ways to work around this are to
Option #1 Use / Create a strongly named type like the following
Structure Item
Public ID as Integer
Public Name As String
Public Description As String
End Structure
Option #2 Set the return type to be Object
and access the list in a late bound manner
EDIT
As CodeInChaos it is possible to return them in a strongly type manner in a generic context. But that doesn't appear to help you for this particular problem.
精彩评论