[英]C# struct compile errors
這是一個功課,我們不學習C#中的結構(我現在正在學習)。 所以我去了msdn,但是我找不到我的程序的問題...是的,我無法完全分配給我的本地語言,而且我不會理解編譯器的想法。
我的作業的UML :(我們必須使用它)接口:IComparable
我們不能實施其他方法或參數。
我用Java編寫這個功課,並且正常工作。
我有一個大問題,我不明白以下錯誤是什么意思:
錯誤2在將控制權返回給調用者之前,必須完全分配自動實現的屬性“Rational.Rational.Denominator”的后備字段。 考慮從構造函數初始化程序中調用默認構造函數。
錯誤3必須完全分配自動實現的屬性“Rational.Rational.Numerator”的備份字段,然后才能將控制權返回給調用者。 考慮從構造函數初始化程序中調用默認構造函數。
錯誤4在分配所有字段之前,不能使用“this”對象
我的代碼:命名空間Rational
{
// (Rational is underline) here the 2 and 3 error
public struct Rational : IComparable<Rational>
{
public long Numerator { get; set; }
public long Denominator { get; set; }
public Rational(long num, long den)
{
// and here (GCD is underline) the 4. error
long simple = GCD(num, den);
this.Numerator = num/simple;
this.Denominator = den/simple;
}
public long GCD(long a, long b)
{
long c = Math.Abs(a);
long d = Math.Abs(b);
if (d == 0) return c;
return GCD(d, c % d);
}
public override string ToString()
{
if (Denominator==1)
{
return Numerator + "";
}
return Numerator+"/"+Denominator;
}
public override bool Equals(object obj)
{
bool result = false;
if (obj is Rational)
{
Rational r = (Rational)obj;
result = this.Equals(r);
}
return result;
}
public bool Equals(Rational r)
{
if ((object)r ==null)
{
return false;
}
return this.Denominator == r.Denominator && this.Numerator == r.Numerator;
}
public int CompareTo(Rational other)
{
...
您可以將this()
添加到構造函數中,也可以使用字段支持的屬性替換auto-properties。
public Rational(long num, long den)
{
// and here (GCD is underline) the 4. error
long simple = GCD(num, den);
this.Numerator = num;
this.Denominator = den;
}
在為支持屬性的自動生成字段分配值之前,可以在此處訪問實例方法GCD
。
您應該將此方法設為靜態。
接下來,您將再次收到相同的錯誤,這次是因為您訪問了自動屬性Numerator
。 您可以通過保留自動屬性並將:this()
添加到構造函數來解決此問題:
public Rational(long num, long den)
:this()
{
這導致在您自己的構造函數代碼運行之前將字段初始化為0
。
替代方案是切換到字段:
public struct Rational : IComparable<Rational>
{
private long _numerator;
private long _denominator;
public long Numerator { get{return _numerator;}; set{_numerator=value;} }
public long Denominator{ get{return denominator;}; set{_denominator=value;} }
public Rational(long num, long den)
{
// and here (GCD is underline) the 4. error
long simple = GCD(num, den);
this._numerator = num;
this._denominator = den;
}
除此之外,您的代碼還有更多問題:
1)您正在使用可變結構。 這通常是糟糕的設計。 從您的屬性中刪除setter或將其設為私有。
2)你沒有覆蓋GetHashCode()
以與Equals
一致(或者它沒有在你的代碼摘錄中顯示)
3)我建議實現IEquatable<Rational>
。 您已經實現了Equals(Rational)
,因此您無需添加任何其他方法。
4)您的代碼很容易產生int溢出。 考慮使用BigInteger
而不是long
。
5)除非你將你的理性歸一化(分母> 0並且用GCD除以),否則你得到的數學上等價的理性數不能相等。
您需要調用默認構造函數才能使其工作:
public Rational(long num, long den) : this()
{
// and here (GCD is underline) the 4. error
long simple = GCD(num, den);
this.Numerator = num;
this.Denominator = den;
}
這里一個更大的問題是你有一個可變的結構。 這絕不是一個好主意。 我會成功的:
public long Numerator {get; private set;}
我在Rational
的構造函數中注意到你正在調用GCD並將結果存儲為simple
,但是你不使用結果。
使您的GCD
功能保持靜態。
它不使用任何實例成員,並且因為它在實例成員設置之前被調用,所以它不能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.