I am sure i am doing开发者_Python百科 something terribly wrong, but i should better ask the experts.
At the third line i get the error Value of type <anonymous type> cannot be converted to <anonymous type>
Dim Query = (From c In Db.web Select New With {.AA = c.AA}).ToList
Dim v = New With {.Amount = 108}
Query.Add(v)
What am i missing here?
Because you have named your fields differently (and maybe it has different type as well, I don't know, cause I don't know what type c.AA
is), compiler has created different type for v
, so you have 2 anonymous classes, with different fields (even if they have same type, but their name differs) and they are not compatible with each other.
I don't know VB.Net well, but something like this:
Dim Query = (From c In Db.web Select New With {.Amount = CInt(c.AA)}).ToList Dim v = New With {.Amount = 108} Query.Add(v)
Should solve the problem, at least works in C#
.
Anonymous type identity is based not just on the types of the members, but on their names as well. So these two objects are of different types, even though to human eyes they have the 'same' structure:
Dim a = New With { .Name = "Bob" }
Dim b = New With { .Moniker = "Robert" }
So even if c.AA
is an Integer
, that's not enough for Query
and v
to be type-compatible.
Obviously your code is distilled from your real problem, so I can't say exactly what you should be doing instead, but perhaps using a named rather than an anonymous type will solve your problem.
This is documented in the VB.NET Spec (from eg version 9.0 here), section 11.10.4 "Anonymous Object-Creation Expressions" (my emphases) :
If two anonymous class creation expressions occur within the same method and yield the same resulting shape—if the property order, property names, and property types all match—they will both refer to the same anonymous class.
Annotation
It is possible that a compiler may choose to unify anonymous types further, such as at the assembly level, but this cannot be relied upon at this time.
By contrast to the annotation, I believe that for C#, the compiler does guarantee anonymous type identity across an assembly when everything matches.
精彩评论