var keyword isn't inferring the type of RepeaterItem, why is that?
This is a quick one. I have the following code:
foreach (var item in myRepeater.Items)
{
MyViewModelItem x = new MyViewModelItem();
MapToEntity(x, item);
myList.Add(report);
}
void MapToEntity(object entity, Control control);
I expected this code to compile with no problems. It didn't, however.
It resulted in a compile time error saying that the method "MapToEntity"开发者_如何学编程 has some invalid arguments. The compiler failed to infer the type of the RepeaterItem, it recognizes it as a plain System.Object.Why is this happening? Am I missing something?
Ps: I fixed the code by deleting the var keyword and explicitly defining the type of the item "RepeaterItem".RepeaterItemCollection does not implement IEnumerable<RepeaterItem>
just plain IEnumerable
. Thus, it's impossible for the compiler in infer the type.
First, your code sample shows that you are using a variable named "item" in the foreach statement and then declaring one of another type below it.
Second the reason you probably seeing it as type Object is that myRepeater.Items is probably a general collection and not a specifically typed one so it would return of type Object. You can specifically state of what type in the ForEach loop and it will return objects of that type if any exist.
A possible solution would be to do myRepeater.Items.OfType() and then you could use the var keyword.
As Anton said, the Items only implements IEnumerable which is why it cannot infer the type.
One thing that you may find useful though is the Cast method.
myRepeater.Items.Cast<RepeaterItem>()
Whilst your example is simple enough for this to not really be needed it may help for more complex examples where you need a typed enumerable.
精彩评论