gpt4 book ai didi

C# ValueType 等于不比较属性?

转载 作者:行者123 更新时间:2023-11-30 20:51:12 24 4
gpt4 key购买 nike

以下打印等于:

struct A
{
int x;
public A(int _x) { x = _x; }
public int Y
{
get
{
Random r = new Random();
return r.Next(0, 1000);
}
}
}

static void Main(string[] args)
{
A a1 = new A(1),a2 = new A(1);
if (a1.Equals(a2))
{
Console.Write("Equals");
}
else
{
Console.Write("Different");
}
}

在这种情况下,有没有办法让 C# 返回 false?意思是,在比较值类型时考虑属性?

最佳答案

写等于然后按“tab”键两次:

// override object.Equals
public override bool Equals(object obj)
{


if (obj == null || GetType() != obj.GetType())
{
return false;
}

// TODO: write your implementation of Equals() here
throw new NotImplementedException();
return base.Equals(obj);
}

这是一个自动生成的片段。现在您可以尝试类似的操作:

// override object.Equals
public override bool Equals(object obj)
{

// checks for A versus A
if (obj == null || GetType() != obj.GetType())
{
return false;
}

// TODO: write your implementation of Equals() here
throw new NotImplementedException();
int compareThis=(A)obj.x;
return ((A)base).x==compareThis; // maybe casting is not needed
}

关于C# ValueType 等于不比较属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21966135/

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