如何在 C# 中复制和比较对象实例?
假设我有一个类MyClass
。然后我有一个此类的实例,例如:
MyClass myobject = ...
然后我想做两件事:
- 将实例复制到另一个对象。
- 比较两个实例以检查它们是否相同(相等)。
最简单的解决方案是什么?我在网上搜索了很多解决方案,但没有一个像我想象的那么简单。
Suppose I have a class MyClass
. Then I have an instance of this class like:
MyClass myobject = ...
Then I want to do 2 things:
- Copy the instance to another object.
- Compare two instances to check if they are the same (equal).
What's the simplest solution for this? I have searched the internet and found many solutions, but none of them are as simple as I expected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的班级中实施 IEquatable(t)。您可以在 Equals() 方法中实现自己的比较逻辑。
您可能还想查看 ICloneable。
Implement IEquatable(t) in your class. You can implement your own comparison logic in the Equals() method.
You might also want to check out ICloneable.
我认为不仅要处理对象引用,还要处理内容。为此,您必须在
MyClass
类中实现IClonable
接口。您必须在
Myclass
类中实现IEquatable
接口。I assume not just coping the object reference but coping the content. For this purpose you have to implement
IClonable
interface in yourMyClass
class.You have to implement
IEquatable
interface in yourMyclass
class.正如其他人指出的相等比较,实现 IEquatable 或只是重写 Equals() 和 GetHashCode() 方法。
在 C# 等内存管理语言中,克隆(复制)并不是一个小问题,因为您不能只复制内存。实现 IClonable 是一种可能性,但从客户的角度来看,您会混淆是否执行深克隆和浅克隆。
根据我的经验,实现克隆的最简单方法之一是使类可序列化,然后简单地对其进行序列化和反序列化。当然,您还可以获得可序列化对象的其他好处。
As others have pointed out for equality comparison, implement IEquatable or just override the Equals() and GetHashCode() methods.
Cloning (copying) is not a trivial problem in memory-managed languages like C#, since you can't just copy memory. Implementing IClonable is one possibility, but there will be confusion from the client perspective of whether you are performing deep vs. shallow cloning.
In my experience, one of the simplest ways to implement cloning is to make a class serializable, and simply serialize and deserialize it. And, of course, you will reap other benefits to having a Serializable object as well.