内容简介:http://stackoverflow.com/questions/15619407/why-do-i-have-to-copy-this-when-using-linq-in-a-struct-and-is-it-ok-if-i-do
下面的代码包含一个不可变结构中的简单LINQ查询.
struct Point
{
static readonly List</*enum*/> NeighborIndexes;
//and other readonly fields!
public IEnumerable<FlatRhombPoint> GetEdges()
{
return from neighborIndex in NeighborIndexes;
select GetEdge(neighborIndex);
}
}
它不编译
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.
有谁知道为什么这是不允许的?
修复消息建议工作正常:
public IEnumerable<FlatRhombPoint> GetEdges()
{
var thisCopy = this;
return from neighborIndex in NeighborIndexes;
select thisCopy.GetEdge(neighborIndex);
}
但这是标准做法吗?有没有在结构体中没有这样的问题的原因?
(在制作副本的更大的方案中,不用担心我的性能本身).
调用结构体的实例方法,并引用这个 –
a hidden ref
parameter
.
这就是为什么struct方法能够突破它们被调用的结构体.
当您在lambda表达式或LINQ查询中使用此(或任何其他本地变量/参数)时,编译器将其变为 compiler-generate closure class 上的字段.
CLR不支持引用字段,所以捕获它将不可能像常规这样工作. (这也是您不能在lambdas内使用ref参数的原因)
迭代器方法具有相同的问题 – 它们被编译成隐藏的枚举器类,并且所有变量或参数都成为类中的字段(这就是为什么迭代器不能使用参数参数).
然而,对于迭代器,C#做出了相反的决定.在一个迭代器中,你是
can use this
,但它将被复制到枚举器类的一个字段.
这意味着如果你在一个迭代器中变换一个结构体,突变不会发生在调用者的副本上.
http://stackoverflow.com/questions/15619407/why-do-i-have-to-copy-this-when-using-linq-in-a-struct-and-is-it-ok-if-i-do
以上所述就是小编给大家介绍的《c# – 为什么在结构体中使用LINQ时必须复制“this”(如果我这样做,可以吗?)?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- MySQL复制表结构和数据
- Kafka Topic 体系结构:复制、故障转移、并行处理
- MongoDB复制选举原理及复制集管理
- MySQL组复制MGR(二)-- 组复制搭建
- Redis系列(四):Redis的复制机制(主从复制)
- JavaScript中对象的浅复制和深复制 原 荐
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Is Parallel Programming Hard, And, If So, What Can You Do About
Paul E. McKenney
The purpose of this book is to help you understand how to program shared-memory parallel machines without risking your sanity.1 By describing the algorithms and designs that have worked well in the pa......一起来看看 《Is Parallel Programming Hard, And, If So, What Can You Do About 》 这本书的介绍吧!