Sto provando a confrontare due strutture usando equals (==) in C#. Il mio struct è qui sotto:Confronto tra due strutture usando ==
public struct CisSettings : IEquatable<CisSettings>
{
public int Gain { get; private set; }
public int Offset { get; private set; }
public int Bright { get; private set; }
public int Contrast { get; private set; }
public CisSettings(int gain, int offset, int bright, int contrast) : this()
{
Gain = gain;
Offset = offset;
Bright = bright;
Contrast = contrast;
}
public bool Equals(CisSettings other)
{
return Equals(other, this);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var objectToCompareWith = (CisSettings) obj;
return objectToCompareWith.Bright == Bright && objectToCompareWith.Contrast == Contrast &&
objectToCompareWith.Gain == Gain && objectToCompareWith.Offset == Offset;
}
public override int GetHashCode()
{
var calculation = Gain + Offset + Bright + Contrast;
return calculation.GetHashCode();
}
}
Sto cercando di avere struct come una proprietà nella mia classe, e consiglia di controllare per vedere se la struct è uguale al valore che sto cercando di assegnarlo a, prima di andare avanti e farlo, quindi non sto indicando la proprietà è cambiata quando non ha, in questo modo:
public CisSettings TopCisSettings
{
get { return _topCisSettings; }
set
{
if (_topCisSettings == value)
{
return;
}
_topCisSettings = value;
OnPropertyChanged("TopCisSettings");
}
}
Tuttavia, sulla linea in cui posso controllare per l'uguaglianza, ottengo questo errore:
Operator '==' cannot be applied to operands of type 'CisSettings' and 'CisSettings'
Non riesco a capire perché questo sia accadendo, qualcuno potrebbe indicarmi la giusta direzione?
ne dite di usare 'Equals()'? –
Equals funziona bene, mi chiedo solo perché il mio override di == non funziona – JMK
@ JMK, forse perché non l'hai sovrascritto ... :) – gdoron