【发布时间】:2019-05-17 07:04:46
【问题描述】:
我知道一个类的一个实例不等于同一个类的另一个实例,即使两个实例都包含属性和实例的字段包含相同的值。例如,在下面的代码中,即使 TestClass 的两个实例的 TestValue01 和 TestValue02 属性的值相同,比较将等于 false 并且将打印 "Boooo!"。
static void Main(string[] args)
{
TestClass testClassInstance01 = new TestClass(1, 1);
TestClass testClassInstance02 = new TestClass(1, 1);
if (testClassInstance01 == testClassInstance02)
{
Console.WriteLine("Woohoo!");
}
else
{
Console.WriteLine("Boooo!");
}
}
class TestClass
{
public int TestValue01 { get; private set; }
public int TestValue02 { get; private set; }
public TestClass(int testValue01, int testValue02)
{
TestValue01 = testValue01;
TestValue02 = testValue02;
}
}
是否有可能强制这种比较等同于真实?
显而易见的事情是比较属性值,如下所示,但我很好奇这是否可以避免。
if (testClassInstance01.TestValue01 == testClassInstance02.TestValue01
&& testClassInstance01.TestValue02 == testClassInstance02.TestValue02)
{
Console.WriteLine("Woohoo!");
}
else
{
Console.WriteLine("Boooo!");
}
编辑
为了完整起见,我正在寻找的是operator overloading。下面是我要求这个例子返回 true 的代码:
class TestClass
{
public int TestValue01 { get; private set; }
public int TestValue02 { get; private set; }
public TestClass(int testValue01, int testValue02)
{
TestValue01 = testValue01;
TestValue02 = testValue02;
}
public static bool operator==(TestClass tc01, TestClass tc02)
{
return tc01.TestValue01 == tc02.TestValue01 && tc01.TestValue02 == tc02.TestValue02;
}
public static bool operator!=(TestClass tc01, TestClass tc02)
{
return tc01.TestValue01 != tc02.TestValue01 || tc01.TestValue02 != tc02.TestValue02;
}
}
【问题讨论】:
-
@MongZhu 你的权利,这正是我所追求的。不过,我目前无法将此问题标记为重复。不知道为什么(可能是等待编辑?)...
标签: c# class comparison