【发布时间】:2016-08-24 13:35:39
【问题描述】:
我已将代码简化为以下重现错误的简短示例。我正在尝试将派生类的值绑定到控件。派生类和绑定逻辑是:
bindingSource = new BindingSource();
numericUpDown1.DataBindings.Add("Value", bindingSource, nameof(SinglePoint.Val), false, DataSourceUpdateMode.OnPropertyChanged);
bindingSource.DataSource = new[] { new SinglePoint(100) };
[...]
public class SinglePoint : PointList
{
public SinglePoint(int val) { points.Add(val); }
public int Val
{
get { return points[0]; }
set
{
if (value > 300) value = 300; //(*)
points[0] = value;
}
}
}
因此,例如在NumericUpDown 上设置值 500 时,离开它后我们应该看到 300,因为 (*) 行。如果基类未实现GetHashCode,则此方法有效:
public class PointList
{
protected List<int> points = new List<int>();
public PointList() { }
// UNCOMMENT this and the binding will stop working properly
//public override int GetHashCode()
//{
// unchecked
// {
// int hashCode = 17;
// foreach (var item in points)
// hashCode += 13 * item.GetHashCode();
// return hashCode;
// }
//}
}
但是,如果您尝试取消注释 GetHashCode 实现,绑定将会中断。这意味着在设置 500 并离开 NumericUpDown 之后,控件仍将显示 500,但实际上基础值将是 300。为什么会发生这种情况,如何在不关闭 GetHashCode 的自定义实现的情况下解决它?
编辑
正如你们中的一些人所指出的,GetHashCode 不应更改,因为它被绑定机制使用。这是对我问题的第一部分的答复。但是,如何使我的 PointList 类满足另一个 rule 的要求,“如果两件事相等 (Equals(...) == true) 那么它们必须为 GetHashCode() 返回相同的值 em>”。如果我有两个 PointList 对象具有相同的点列表(序列),我希望它们被发现相等(因为我的代码中的其他逻辑),这应该意味着具有相同的哈希码。你会怎么做?
【问题讨论】:
标签: c# winforms data-binding