Skip to main content
 首页 » 编程设计

C# 列表自定义对象之间的比较

2024年02月05日9luoye11

Pair<BoardLocation, BoardLocation> loc = new Pair<BoardLocation, BoardLocation>( this.getLocation(), l ); 
if(!this.getPlayer().getMoves().Contains( loc )) { 
    this.getPlayer().addMove( loc ); 
} 

我正在使用我创建的名为“Pair”的类型,但是,我正在尝试使用 C# 中的 contains 函数来比较这两种类型,但是,我在类型“Pair”本身中使用了 override 来进行比较被比较的两个 Pair 对象的“ToString()”。所以有 4 个字符串被比较。两个键和两个值。如果两个 Key 相等,则比较两个值。这是有道理的,因为 key 是被攻击的位置(值)的原始( key )位置。如果键和值相同,则不应添加该对象。

public override bool Equals( object obj ) { 
    Pair<K, V> objNode = (Pair<K, V>)obj; 
    if(this.value.ToString().CompareTo( objNode.value.ToString() ) == 0) { 
        if(this.key.ToString().CompareTo( objNode.key.ToString() ) == 0) { 
            return true; 
        } else 
            return false; 
    } else { 
        return false; 
    } 
} 

问题是,是否有更好的方法可以做到这一点,既不涉及愚蠢的代码量,也不创建新的对象来处理这个问题。当然,如果有任何想法涉及这些,我会洗耳恭听。让我感到困惑的部分是,也许我不明白发生了什么,但是,我希望 C# 提供一种方法,它只是值的等价而不是对象内存位置等。

我也刚刚从 Java 移植了这个,它的工作原理完全一样,但是,我问这个问题是针对 C# 的,因为我希望有一个更好的方法来比较这些对象而不使用 ToString( ) 与通用类型。

请您参考如下方法:

通过使用 && 并只返回相等比较的值,而不是所有那些 if 语句和 return true,您绝对可以使这段代码更简单; 或 return false; 语句。

public override bool Equals (object obj) { 
    // Safety first: handle the case where the other object isn't 
    // of the same type, or obj is null. In both cases we should 
    // return false, rather than throwing an exception 
    Pair<K, V> otherPair = objNode as Pair<K, V>; 
    if (otherPair == null) { 
        return false; 
    } 
 
    return key.ToString() == otherPair.key.ToString() && 
        value.ToString() == otherPair.value.ToString(); 
} 

在 Java 中,您可以使用 equals 而不是 compareTo。

请注意,它们完全与==(和Equals)使用序数比较而不是文化敏感的一个 - 但我怀疑无论如何这就是你想要的。

我个人会回避通过 ToString() 表示来比较值。我会改用键和值类型的自然相等比较:

public override bool Equals (object obj) { 
    // Safety first: handle the case where the other object isn't 
    // of the same type, or obj is null. In both cases we should 
    // return false, rather than throwing an exception 
    Pair<K, V> otherPair = objNode as Pair<K, V>; 
    if (otherPair == null) { 
        return false; 
    } 
 
    return EqualityComparer<K>.Default.Equals(key, otherPair.key) && 
        EqualityComparer<K>.Default.Equals(value, otherPair.value); 
} 

(正如 Avner 所说,您当然可以只使用 Tuple...)

如评论中所述,我还强烈建议您开始使用属性和 C# 命名约定,例如:

if (!Player.Moves.Contains(loc)) { 
    Player.AddMove(loc); 
}