寻找相同的对象名称,然后比较结构

编程入门 行业动态 更新时间:2024-10-25 21:23:24
本文介绍了寻找相同的对象名称,然后比较结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

你好, 我想: 用对象填充列表 如果object.name出现多次 然后 比较两者的结构 如果两个结构都相同 显示消息框(或其他内容) 其他 什么都不做 简单比较有什么问题,例如:

Hi there I wanted to: fill a list with objects if a objects.name occurs more than once then compare the structure of the two if the both structures are the same show messagebox (or just something) else do nothing Whats wrong with simply comparison like:

if (oObjList.Contains(oObj))

我已经提前感谢了

i thank already in advance

推荐答案

我假设我们正在使用列表< T> [ ^ ]来实现您的对象列表. 如果您阅读了列表< T> ;.包含方法 [ ^ ]和IEquatable<T> ;.等于方法 [ ^ ],您将看到,如果列表中存储的所有对象都实现了IEquatable接口,则您的语句将起作用. > 在如下对象中定义Equals函数: I am assuming that we are using List <T>[^] to implement your list of objects. If you read the documentation of the List<T>.Contains Method[^] and IEquatable<T>.Equals Method[^] you will see that your statement will work if all the objects stored in the list implement the IEquatable interface. Define the Equals function in the objects like: public override bool Equals(Object obj)

通过此实现,当对象属于不同类型时,您可以返回false,请参见接口文档中的示例.

with this implementation you can return false when the objects are of different types, see the sample in the interface documentation.

您是否控制对象属于实例的类?如果是这样,您可以覆盖Equals和==,以便a == b返回您想要的内容.例如一个简单的例子 Do you control the class of which the objects are instances? If so, you can override Equals and == so that a == b returns what you want. E.g, a trivial example class Test { int a; double b; public static operator bool == (Test a, Test b) { return (object)a == null ? (object)b == null : a.Equals(b); } public static operator bool != (Test a, Test b) { return !(a == null); } public override bool Equals(object o){ if(o is Test){ Test test = (Test)o; return a == test.a && b == test.b; } else return base.Equals(o); } public override int GetHashCode(){ return a.GetHashCode() ^ b.GetHashCode(); } }

如果不是,并且您事先不知道对象是什么类型,则需要使用反射,对它们的字段/属性/等进行排序(无论您算作结构"如何)并进行比较.

If not, and you don''t know in advance what type the objects will be, you''ll need to use reflection, make a sorted list of their fields/properties/etc (whatever you count as ''structure'') and compare those.

现在这是我的解决方案(关键字LINQ): Now here''s my solution (keyword LINQ): public void AddType(PvssType dpt) { if (this.Any(tp => tp.n.Name == dpt.n.Name))return; this.Add(dpt); }

更多推荐

寻找相同的对象名称,然后比较结构

本文发布于:2023-10-30 18:57:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543715.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   名称   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!