Skip to main content
 首页 » 编程设计

c#之检查 ListMyClass> 是否包含某些 MyClass 对象的副本的正确方法是什么

2024年02月06日16mfryf

我的结构非常复杂:

public static List<state> states = new List<state>(); 
public class state : List<situation> { } 
public class situation { 
    //public rule rule; //another complex object 
    public int pos; 
    public string term; 
 
    public situation(/*rule rule,*/ string terminal, int pointPosition) { 
        //this.rule = rule; 
        this.term = terminal; 
        this.pos  = pointPosition; 
    } 
} 

在我的程序中,我生成了新的 state 对象,这些对象必须添加到 states 列表中。但前提是此列表中的 state 不相同(state 列表中的 situation 对象的顺序无关紧要,并且可以不同两个 state 实际上是相等的)。

我试过这个:

states.Add(new state()); 
states[0].Add(new situation("#", 0)); 
 
state s = new state(); 
s.Add(new situation("#", 0)); 
 
if (states.Contains(s)) { 
    Console.WriteLine("HODOR"); //not performed 
} 

看起来 Contains 不适用于自定义对象,所以我必须创建一些自定义方法。

我可以只比较每个对象和每个字段,但是……这看起来是非常乏味和丑陋的解决方案。可能这里有更好的方法来做到这一点?

请您参考如下方法:

在您的情境类中重写Equals 并实现您自己的相等性,即:

public class situation  
{ 
      public string Terminal  
      { 
         get{ return term;} 
      } 
 
      public int Pos 
      { 
         get{ return pos;} 
      } 
 
      public override bool Equals(object obj) 
      { 
         bool result; 
         situation s = obj as situation; 
         if (s != null) 
         { 
            result = Terminal.Equals(s.Terminal) && Pos == s.Pos; 
         } 
 
         return result; 
      } 
}