我只需要一点确认...
我正在像这样填充我的组合框:
myCombo.Items.Add(new ComboBoxInt32Data("Red", 0));
myCombo.Items.Add(new ComboBoxInt32Data("Green", 1));
myCombo.Items.Add(new ComboBoxInt32Data("Yellow", 2));
myCombo.Items.Add(new ComboBoxInt32Data("Blue", 3));
现在,当我从数据库表中检索值时,我只有整数值。
我覆盖的 Equals 看起来与 msdn 的建议完全相同:
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
ComboBoxInt32Data data = obj as ComboBoxInt32Data;
if ((object)data == null)
{
return false;
}
return (m_Name.ToUpper() == data.Name.ToUpper() && m_Value == data.Value);
}
但是,正如我所提到的,我只有价值。我不想去做以下事情:
Int32 DatabaseValue = SomeFunctionThatRetrivedMeThisIntValueFromDB();
string TheValueName = SomeFunctionThatDoesALookUpToGetTheName(DatabaseValue);
myCombo.SelectedIndex = myCombo.Items.IndexOf(new ComboBoxInt32Data(TheValueName, DatabaseValue));
我宁愿只做以下事情:
myCombo.SelectedIndex = myCombo.Items.IndexOf(SomeFunctionThatRetrivedMeThisIntValueFromDB());
所以,我的确认是,在我的 Equals 中执行以下操作是否可以(如,这是一个可接受的最佳实践)(查找“添加这个”):
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
// added this
if (obj is Int32)
{
Int32 value = (Int32)obj;
return m_Value == value;
}
ComboBoxInt32Data data = obj as ComboBoxInt32Data;
if ((object)data == null)
{
return false;
}
return (m_Name.ToUpper() == data.Name.ToUpper() && m_Value == data.Value);
}
谢谢!