在这里讨论了SO之后,我已经多次读过可变结构是"邪恶"的评论(就像这个问题的答案一样).
C#中可变性和结构的实际问题是什么?
我想创建一个对象的新实例 IEnumerable<object>
我可以这样做吗?
IEnumerable<object> a = new IEnumerable<object>();
Run Code Online (Sandbox Code Playgroud) 是yield return用于实现快捷方式IEnumerable和IEnumerator?
下面的代码在不可变结构中包含一个简单的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)
但这是标准做法吗?是否有理由在结构中没有这样的查询?(在制作副本的更大方案中,并不担心我的表现如此).
c# ×4
struct ×2
ienumerable ×1
ienumerator ×1
immutability ×1
iterator ×1
linq ×1
mutable ×1
yield ×1