gpt4 book ai didi

c# - 当右侧是 Object 类型时如何处理运算符 == 重载

转载 作者:太空狗 更新时间:2023-10-29 23:31:27 24 4
gpt4 key购买 nike

在下面的示例中,我创建了一个名为“Custom”的类,它实现了 IComparable:

public int CompareTo(Object value)
{
// comparison logic here
}

CompareTo(Object) 的实现通常是“宽容的”,因为它们会将“值”转换为更具体的类型。在这种情况下,将执行对类型“Custom”的强制转换,以便进行比较。假设我还重载了 == 运算符:

public static bool operator== (Custom lhs, Custom rhs)
{
// equivalence test here
}

我遇到的问题是在这种情况下:

Custom c = GetCustomObject();
Object o = GetOtherObject();
if(c == o)
{
// will not be true unless c and o are the same object
}

问题是当 == 被调用时,因为 rhs 是“Object”类型,它回退到引用相等性的默认测试 - 不调用重载。

这里的期望是什么?我可以为 == 运算符添加另一个重载:

public static bool operator== (Custom lhs, Object rhs)

但 MSDN 或其他在线示例中明显缺少此​​类示例。这让我认为引用相等性测试是预期的行为

最佳答案

This makes me think that the test for reference equality is the expected behavior

这是正确的。

由于 == 是在变量的静态类型上分派(dispatch)的,因此以任何其他方式实现它很少有用。如果你实现了 ==(YourClass, Object) 那么这个:

YourClass x = new YourClass();
if (x == someObject) { ... }

将表现不同:

Object x = new YourClass();
if (x == someObject) { ... }

这通常是出乎意料的!

因此,如果您想要虚拟分派(dispatch)的相等性,您应该只使用 Equals

System 中只有一种类型实现了具有不同参数类型的==,而且它非常特殊(RuntimeTypeHandle)。

关于c# - 当右侧是 Object 类型时如何处理运算符 == 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21447321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com