2011-07-29 43 views
0

我正在使用CSharp代碼,在構造函數中我需要訪問該類的屬性。從邏輯上講,它對我來說看起來很麻煩,因爲我將訪問那些還在建設中的對象的屬性。我們可以訪問構造函數的屬性

它的舊代碼使用c#版本4.0,我有種重構它,所以這就是爲什麼不能從頭開始重新設計所有東西。

感謝

class employee 
{ 
    employee() 
    { 
    int square = count * count; 
    } 
    private int count {get;set;} 
} 

回答

0

在施工時間,你可以設置一個屬性,但除非它有一個靜態成員的支持得到或者是值類型,你會直到你把它拿到一個空值。

public class WhatClass 
{ 
    public WhatClass() 
    { 
     int theCount = Count; // This will set theCount to 0 because int is a value type 
     AProperty = new SomeOtherClass; // This is fine because the setter is totally usable 
     SomeOtherClass thisProperty = AProperty; // This is completely acceptable because you just gave AProperty a value; 
     thisProperty = AnotherProperty; // Sets thisProperty to null because you didn't first set the "AnotherProperty" to have a value 
    } 

    public int Count { get; set; } 
    public SomeOtherClass AProperty { get; set; } 
    public SomeOtherClass AnotherProperty { get; set; } 
} 
+1

錯誤。你不會得到'NullReferenceException';你只會得到'null'。 – SLaks

+0

@SLaks:噢,恩,謝謝。 –

3

沒有什麼錯,但count永遠是0

除了沒有在構造函數中設置其所有狀態的對象之外,在.Net中幾乎沒有像「部分構造」對象這樣的事物。

1

如果你正在構造這個類,並且之前在構造函數中沒有設置任何屬性,並且沒有一個屬性是靜態的並且在其他地方設置,那麼這些值將是默認值或null,所以沒有必要得到它們的內容包含。否則,構造函數是將屬性設置爲某種東西的理想場所。

0

是的,C#允許這樣做,但有時候更好的是讓私有字段由公共屬性包裝,並且在類方法中只與字段一起工作。在你的情況下,我會建議刪除私有財產,並使用類字段變量。如果你的班級的消費者可能想要訪問一個房產 - 使用私人二傳手將其公開,這種自動房產是私人房地產的另一種選擇。

相關問題