检查 List<MyClass> 是否包含某些 MyClass 对象的副本的正确方法是什么?

What is proper way to check if List<MyClass> contain copy of some MyClass object?

我的结构相当复杂:

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 class 并实现您自己的平等,即:

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;
      }
}

我也加了这个:

public class state : List<situation> {

    public override bool Equals(object obj) {
        state s = obj as state;
        if (s != null) {
            foreach (situation situation in s) {
                if (!this.Contains(situation)) { return false; }
            }

            foreach (situation situation in this) {
                if (!s.Contains(situation)) { return false; }
            }

            return true;
        }
        return false;
    }
}

所以我的示例有效。