我创建了一个代表Fraction的类,如下所示。 我发现很难理解新对象之间的平等问题。任何人都可以解释一下,为什么会发生这种情况;
Fraction f1 = new Fraction(1, 2);
Fraction f2 = new Fraction(1, 2);
if (f1.Equals(f2)) Console.WriteLine("true"); // does not return anything
分数类
class Fraction: IComparable<Fraction>
{
public int Numerator { get; set; }
private int _denominator;
public decimal Decimal
{
get { return (Decimal)Numerator / Denominator; }
private set { }
}
public int Denominator
{
get { return _denominator; }
set {
if (value != 0)
_denominator = value;
else
throw new Exception();
}
}
public Fraction(int num, int den)
{
Numerator = num;
Denominator = den;
}
public Fraction(int num)
{
Numerator = num;
Denominator = 1;
}
public Fraction()
{
}
public override string ToString()
{
return String.Format( "{0}/{1}", Numerator, Denominator);
}
public static Fraction operator *(Fraction f1, Fraction f2)
{
return new Fraction(f1.Numerator * f2.Numerator, f1.Denominator* f2.Denominator);
}
public static Fraction Parse(string str)
{
string[] parts = str.Split('/');
if (parts.Length == 2)
return new Fraction(Int32.Parse(parts[0]), Int32.Parse(parts[1]));
else
throw new Exception("Give a fraction in this form: \"1/4\" ");
}
public int CompareTo(Fraction other)
{
return this.Decimal.CompareTo(other.Decimal);
//throw new NotImplementedException();
}
}