有没有人知道如果你在使用泛型集合时没有实现iequtalable会发生什么?

Jac*_*ada 5 c#

我在这里问了一个问题:何时使用IEquatable以及为什么要使用IEquatable.

来自msdn:

当在Contains,IndexOf,LastIndexOf和Remove等方法中测试相等性时,IEquatable(T)接口由泛型集合对象(如Dictionary(TKey,TValue),List(T)和LinkedList(T))使用.

如果你不实现那个界面究竟发生了什么?异常/默认对象等于/ ref等于?

Dar*_*rov 2

这是一个例子:

public class Foo : IEquatable<Foo>
{
    public string Bar { get; set; }

    public bool Equals(Foo other)
    {
        return string.Equals(other.Bar, Bar);
    }
}

class Program
{

    public static void Main(string[] args)
    {
        var foos = new List<Foo>(new[] 
        { 
            new Foo { Bar = "b1" },
            new Foo { Bar = "b2" },
            new Foo { Bar = "b3" },
        });

        var foo = new Foo { Bar = "b2" };
        Console.WriteLine(foos.IndexOf(foo)); // prints 1
    }
}
Run Code Online (Sandbox Code Playgroud)

现在评论IEquatable<Foo>实现并再次运行程序。