Consider this contrived, trivial example:
var foo = new byte[] {246, 127};
var bar = foo.Cast<sbyte>();
var baz = new List<sbyte>();
foreach (var sb in bar)
{
baz.Add(sb);
}
foreach (var sb in baz)
{
Console.WriteLine(sb);
}
With the magic of Two's Complement, -10 and 127 is printed to the console. So far so good. People with keen eyes will see that I am iterating over an enumerable and adding it to a list. That sounds like ToList
:
var foo = new byte[] {246, 127};
var bar = foo.Cast<sbyte>();
var baz = bar.ToList();
//Nothing to see here
foreach (var sb in baz)
{
Console.WriteLine(sb);
}
Except that does not work. I get this exception:
Exception type: System.ArrayTypeMismatchException
Message: Source array type cannot be assigned to destination array type.
I find this exception very peculiar because
ArrayTypeMismatchException
- I'm not doing anything with arrays, myself. This seems to be an internal exception.
- The
Cast<sbyte>
works fine (as in the first example), it's when using ToArray
or ToList
the problem presents itself.
I'm targeting .NET v4 x86, but the same occurs in 3.5.
I don't need any advice on how to resolve the problem, I've already managed to do that. What I do want to know is why is this behavior occurring in the first place?
EDIT:
Even weirder, adding a meaningless select statement causes the ToList
to work correctly:
var baz = bar.Select(x => x).ToList();
question from:
https://stackoverflow.com/questions/11039479/why-does-this-linq-cast-fail-when-using-tolist 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…