2013-10-16 64 views
0

我已經在C#這個程序,它實現IComparable接口比較車輛的名稱和排序他們成功編譯alphabetically.The代碼,但在執行它給我StackOverFlowExecption.This是我的代碼 -StackOverflowException的原因是什麼?如何解決?

class Vehicle:IComparable 
    { 
    private string vehiclename 
    { 
     get 
     { return vehiclename; 
     } 
     set 
     { 
      vehiclename = value; 
     } 
    } 


    public Vehicle(string name) 
    { 
     vehiclename = name; 
    } 


    int IComparable.CompareTo(Object obj) 
    { 
     Vehicle temp = (Vehicle)obj; 
     return string.Compare(this.vehiclename, temp.vehiclename); 
    } 

    static void Main(string[] args) 
    { 
     Vehicle[] myvehicles = new Vehicle[5]; 
     myvehicles[0] = new Vehicle("Honda City"); 
     myvehicles[1] = new Vehicle("Nano"); 
     myvehicles[2] = new Vehicle("Desire"); 
     myvehicles[3] = new Vehicle("Santro"); 
     myvehicles[4] = new Vehicle("Nissan"); 

     Console.WriteLine("Unordered List of vehicles:"); 
     foreach (Vehicle v in myvehicles) 
      Console.WriteLine(myvehicles); 

     Array.Sort(myvehicles); 

     Console.WriteLine("ordered List of vehicles:"); 
     foreach (Vehicle v in myvehicles) 
      Console.WriteLine(myvehicles); 

    } 
} 

什麼是這種例外的原因,我該如何解決它?

回答

2

getset調用自己:

private string vehiclename 
{ 
    get 
    { return vehiclename; 
    } 
    set 
    { 
     vehiclename = value; 
    } 
} 

那麼訪問該屬性(getset)將導致發生溢出。

我懷疑你要麼需要一個auto-implemented property

private string vehiclename 
{ 
    get; 
    set; 
} 

或提供自己的支持字段:

private string _vehiclename; 
private string vehiclename 
{ 
    get 
    { return _vehiclename; 
    } 
    set 
    { 
     _vehiclename = value; 
    } 
} 

或者可能的話,你不希望在所有的屬性(private屬性相當罕見),只是想要一個領域:

private string vehiclename; 
2
private string vehiclename 
    { 
     get 
     { 
      return vehiclename; 
     } 
     set 
     { 
      vehiclename = value; 
     } 
    } 

您正在用此代碼創建循環!

當您設置一個值,該屬性vehiclename,「價值」被分配給vehiclename,「價值」被分配給vehiclename,「價值」被分配給vehiclename ...

這可以通過重命名來sloved像這樣的屬性:

 private string Vehiclename 
      { 
       get 
       { 
        return vehiclename; 
       } 
       set 
       { 
        vehiclename = value; 
       } 
      } 
    string vehiclename = string.Empty; 
0

您的公關操作會導致堆棧溢出異常。讓我們來看一看:

private string vehiclename 
{ 
    get 
    { return vehiclename; 
    } 
    set 
    { 
     vehiclename = value; 
    } 
} 

當打電話vehiclename的二傳手,它將值的財產vehiclename這就要求二傳手....這當然是一個堆棧溢出。使用屬性時,應堅持自動實現的屬性或有效的後臺字段。

相關問題