简体   繁体   English

equals(LINQ)和==(C#)运算符之间的区别?

[英]Difference between equals (LINQ) and == (C#) operators?

I have been reading Programming Microsoft LINQ in Microsoft .NET Framework 4 , and now I am understanding the join clause in LINQ, but I have a doubt or question respect about its definition; 我一直在阅读Microsoft .NET Framework 4中的Microsoft LINQ编程 ,现在我理解LINQ中的join子句,但我对它的定义有疑问或质疑; in the book it is defines as: 在书中它被定义为:

You can define equality comparisons only by using a special equals keyword that behaves differently from the == operator, because the position of the operands is significant. 您只能通过使用与==运算符不同的特殊equals关键字来定义相等比较,因为操作数的位置很重要。 With equals , the left key consumes the outer source sequence, and the right key consumes the inner source sequence. 使用equals ,左键消耗外部源序列,右键消耗内部源序列。 The outer source sequence is in scope only on the left side of equals , and the inner source sequence is in scope only on the right side. 外部源序列仅在equals的左侧范围内,而内部源序列仅在右侧的范围内。

And there is also a formal definition about this operator: 并且还有关于此运算符的正式定义:

join-clause ::= join innerItem in innerSequence on outerKey equals innerKey

Please, can someone explain me the above concept in other words or by paraphrasing it? 请问,有人可以用其他的话或通过释义来解释我的上述概念吗?

I guess it's because 'equals' in the join doesn't work like == does, and so the language designers decided not to call what it is doing the same thing. 我想这是因为连接中的'equals'不像==那样工作,所以语言设计者决定不调用它做同样的事情。

In C#, it is sort of given that a == b is exactly the same as b == a. 在C#中,有一种给定a == b与b == a完全相同。 In the definition of a join, this is not so: 在连接的定义中,情况并非如此:

var list = from a in ctx.TableA
           join b from ctx.TableB on a.Id equals b.tableAId

This, above, is valid. 以上这个是有效的。

var list = from a in ctx.TableA
           join b from ctx.TableB on b.tableAId equals a.Id

This will not compile. 这不会编译。 What the language spec says is that the 'outer' table (TableA in this case) must be specified first and the inner one (TableB) must be second. 语言规范说的是必须首先指定'外部'表(在本例中为TableA),而内部表(TableB)必须是第二个。 I suppose that the language designers thought that this was sufficiently different from the way that == works that it would be a bad idea to use it and they came up with the idea to use 'equals'. 我认为语言设计者认为这与==的工作方式有很大的不同,使用它是一个坏主意,他们想出了使用'等于'的想法。

I think I'm probably right, but only the language designers involved will really know the truth. 我想我可能是对的,但只有所涉及的语言设计师才能真正了解真相。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM