C#INotifyPropertyChanged在类中没有覆盖Equals方法吗?

时间:2018-06-01 23:22:23

标签: c#

我有一个BindingList<Proxy>,其中类Proxy实现了INotifyPropertyChanged。我也重写了Equals方法,因为如果我有2个具有相同IP和端口的Proxy对象,我希望它们在进行比较时被认为是相等的。

但是,如果我重写Equals方法,则绑定BindingList的DataGridView在引发PropertyChanged事件时不会更新。如果我不重写Equals方法,它可以正常工作。

public class Proxy : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    private string ip;
    private int port;
    private ProxyStatus status;

    public string IP { get { return ip; } set { ip = value; OnPropertyChanged("IP"); } }
    public int Port { get { return port; } set { port = value; OnPropertyChanged("Port"} }
    public ProxyStatus Status { get { return status; } set { status = value; OnPropertyChanged("Status"); } }

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public Proxy(string proxy)
    {
        IP = proxy.Split(':')[0];
        Port = Convert.ToInt32(proxy.Split(':')[1]);
        Status = ProxyStatus.Unknown;
    }

    public override string ToString()
    {
        return this.IP + ":" + this.Port;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }

        Proxy p = obj as Proxy;
        if (p == null)
        {
            return false;
        }

        if (p.ToString() == this.ToString())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public override int GetHashCode()
    {
        return base.GetHashCode();
    }
}

0 个答案:

没有答案