C# 值类型的直接比较
我已阅读以下有关 C# 值类型比较的声明 C# 深入,第二版多次。
第77页,
当类型参数不受约束(没有对其应用任何约束)时,您可以使用 == 和 != 运算符,但只能将该类型的值与 null 进行比较。您无法将 T 类型的两个值相互比较。
...
当类型参数被限制为值类型时,== 和 != 根本不能与它一起使用。
如果我理解正确(我不这么认为),它基本上告诉我你不能 使用 == 或 != 比较两个值类型。为什么为什么为什么?
对于这种情况,如果能给出一个简单的例子就更好了。有人可以给我吗 知道上面这段话想表达什么吗?
I have read the following statement regarding to the comparison of C# value types
in C# in Depth, Second Edition several times.
page 77,
When a type parameter is unconstrained (no constraints are applied to it), you can use == and != operators, but only to compare a value of that type with null. You can’t compare two values of type T with each other.
...
When a type parameter is constrained to be a value type, == and != can’t be used with it at all.
If I understand (I don't think so) it correctly, it basically tells me that you cannot
use == or != to compare two value types. Why why why?
It will be better if a simple example can be given for this case. Can someone give me
a little idea what the above paragraph tries to convey?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它只是在约束到值类型时表示这一点(第二段)
如果没有对泛型的值类型约束,它也表示这一点(第一段)
如果将
T
约束为引用类型,则可以摆脱使用==
It simply means this when constraining to a value type (second paragraph)
Without the value-type constraint on the generic, it also says this (first paragraph)
If you constrain
T
to a reference type, you can get away with using==
对象不可比较,因为使用 == 的比较是测试引用是否相同(内存地址)。您通常会使用 if (string1.Equals(string2))。
我不明白的是,我见过 == 适用于字符串的情况,也见过不适用的情况。
Objects aren't comparable because a comparison using == is testing whether the reference is the same (the memory address). You would normally use if (string1.Equals(string2)).
Something I don't understand is that I have seen circumstances where == works with strings, and circumstances where it doesn't.