2013-05-22 50 views
4
class Program 
{ 
    static void Main(string[] args) 
    { 
     something s = new something(); 
     s.DoIt(10); 
     Console.Write(s.testCount); 
    } 
} 

class something 
{ 
    public int testCount 
    { 
     get { return testCount; } 
     set { testCount = value + 13; } 
    } 

    public void DoIt(int val) 
    { 
     testCount = val; 
    } 
} 

是我所擁有的,因爲我想測試和玩弄C#的getters/setter東西。但是,我得到一個StackOverFlowException未處理「set {testCount = value + 13}」。而且我無法一步步完成,因爲我收到了一個「調試器無法繼續運行流程,流程已終止」的消息。任何想法我做錯了什麼?在getter/setter c中的無限循環#

編輯:今天我瞭解到,我做了一個非常愚蠢的銳皮。鑑於衆多即時響應。現在我知道更好。

+0

你正在訪問setter中的同一個propery。您可能需要有一個私人變量,用於訪問您的公共財產。 (不燃燒,但這段代碼讓我發抖) –

+0

啊。我不太習慣物業的運作方式,我只需要一起扔垃圾,試圖理解一些東西。 –

+0

爲了解釋無限循環,@ToonCasteele的含義是,既然你在*自己的setter *中調用了'testCount'的set方法,實際的set方法會自己調用它自己。 – tnw

回答

17

您有一個無限遞歸,因爲您指的是屬性屬性。

您應該使用支持字段此:

private int testCount; 
public int TestCount 
{ 
    get { return testCount; } 
    set { testCount = value + 13; } 
} 

注意屬性名TestCount(這也符合C#命名標準),而不是字段名testCount(小寫t)。

4

你應該聲明一個變量來支持此屬性:

class something 
{ 
    private int _testCount; 
    public int testCount 
    { 
     get { return _testCount; } 
     set { _testCount = value + 13; } 
    } 
    ... 
2

此:

public int testCount 
{ 
    get { return testCount; } 

它返回自身,從而導致它運行病毒。

不是自己返回自己的屬性,而是將目標值存儲在另一個(最好是protected或private)變量中。然後在setter和getter中操作該變量。

1
class Program 
{ 
    static void Main(string[] args) 
    { 
     something s = new something(); 
     s.DoIt(10); 
     Console.Write(s.testCount); 
    } 
} 

class something 
{ 
    private int _testCount; 

    public int testCount 
    { 
     // you are calling the property within the property which would be why you have a stack overflow. 
     get { return _testCount; } 
     set { _testCount = value + 13; } 
    } 

    public void DoIt(int val) 
    { 
     testCount = val; 
    } 
} 
3

您在屬性的getter中有循環引用。試試這個:

class Something 
{ 
    private int _testCount; 
    public int TestCount 
    { 
     get { return _testCount; } 
     set { _testCount = value; } 
    } 

    public void DoIt(int val) 
    { 
     _testCount = val; 
    } 
}