The code belows contains a simple LINQ query inside an immutable struct.
struct Point
{
static readonly List</*enum*/> NeighborIndexes;
//and other readonly fields!
public IEnumerable<FlatRhombPoint> GetEdges()
{
return from neighborIndex in NeighborIndexes;
select GetEdge(neighborIndex);
}
}
It does not compile.
Anonymous methods, lambda expressions, and query expressions inside
structs cannot access instance members of 'this'. Consider copying
'this' to a local variable outside the anonymous method, lambda
expression or query expression and using the local instead.
Does any one know why this is not allowed?
The fix the message suggests works fine:
public IEnumerable<FlatRhombPoint> GetEdges()
{
var thisCopy = this;
return from neighborIndex in NeighborIndexes;
select thisCopy.GetEdge(neighborIndex);
}
But is this standard practice? Are there reasons for not having queries like this in structs?
(In the bigger scheme of things making a copy does not worry me performance-wise as such).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…