你好, 我想: 用对象填充列表 如果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); }
更多推荐
寻找相同的对象名称,然后比较结构
发布评论