下面的代码在不可变结构中包含一个简单的LINQ查询.
struct Point
{
static readonly List</*enum*/> NeighborIndexes;
//and other readonly fields!
public IEnumerable<FlatRhombPoint> GetEdges()
{
return from neighborIndex in NeighborIndexes;
select GetEdge(neighborIndex);
}
}
Run Code Online (Sandbox Code Playgroud)
它不编译.
结构体内的匿名方法,lambda表达式和查询表达式无法访问"this"的实例成员.考虑将'this'复制到匿名方法,lambda表达式或查询表达式之外的局部变量,并使用local.
有谁知道为什么不允许这样做?
修复消息建议工作正常:
public IEnumerable<FlatRhombPoint> GetEdges()
{
var thisCopy = this;
return from neighborIndex in NeighborIndexes;
select thisCopy.GetEdge(neighborIndex);
}
Run Code Online (Sandbox Code Playgroud)
但这是标准做法吗?是否有理由在结构中没有这样的查询?(在制作副本的更大方案中,并不担心我的表现如此).
我有这种情况(大大简化):
interface IPoint<TPoint>
where TPoint:IPoint<TPoint>
{
//example method
TPoint Translate(TPoint offset);
}
interface IGrid<TPoint, TDualPoint>
where TPoint:IPoint<T
where TDualPoint:Ipoint
{
TDualPoint GetDualPoint(TPoint point, /* Parameter specifying direction */);
}
Run Code Online (Sandbox Code Playgroud)
这是典型的实现:
class HexPoint : IPoint<HexPoint> { ... }
class TriPoint : IPoint<TriPoint> { ... }
class HexGrid : IGrid<HexPoint, TriPoint> { ... }
class TriGrid : IGrid<TriPoint, HexPoint> { ... }
Run Code Online (Sandbox Code Playgroud)
所以在a上HexGrid,客户端可以调用双网格上的点,具有完全正确的类型:
TriPoint dual = hexGrid.GetDualPoint(hexPoint, North);
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好; 客户端不需要知道关于两点如何关联的类型的任何信息,她需要知道的是HexGrid该方法GetDualPoint返回一个TriPoint.
除了...
我有一个充满通用算法的类,它们在IGrids …