2012-11-29 58 views
2

可以說我有這個類叫做class1,class1包含一個默認構造函數和一個接受一個參數(比如說一個字符串)的構造函數。在該構造函數中,我設置了一個變量,我們稱之爲「string var」。我希望var從創建該對象時傳遞給構造函數的字符串中獲取值,但我希望能夠在構造函數作用域之外使用var,那有可能嗎?因爲構造函數不返回值和什麼。簡單的構造函數問題

澄清這裏是我想要做的代碼示例:

class class1 
{ 
    public class1(string songPath) 
    { 
     System.Media.SoundPlayer songPlayer = new System.Media.SoundPlayer(songPath); 
    } 
//here I want to use my songPlayer I created with the passed string as songPath 
} 

回答

4

你需要讓songPlayer場 - 它是一個局部變量只是它的時刻宣佈在構造函數中可見。

private System.Media.SoundPlayer songPlayer; 

public class1(string songPath) 
{ 
    songPlayer = new System.Media.SoundPlayer(songPath); 
} 
+0

謝謝,這個工作很好,將來會有很好的用處。我猜想,我有時間閱讀一些信息。 – Jacco

1

就這樣

//System.Media.SoundPlayer _songPlayer ; 
public System.Media.SoundPlayer songPlayer 
{ 
    //if you have nay logic to handle ull 
//get{ if(_songPlayer != null) return _songPlayer; else null; } or just 
    get; 
} 


public class1(string songPath) 
{ 
    SongPlayer = new System.Media.SoundPlayer(songPath); 
    //_songPlayer = new System.Media.SoundPlayer(songPath); 
} 

注創建屬性:有益的,如果你想用這個成員課外否則它能夠更好地去解決@Oded ..

和使用私人vriable財產,如果你想處理空情況

+0

該屬性添加的字段是什麼? – Oded

+0

@Oded - 我想如果他想在課堂以外使用...... –

+0

OP沒有在課堂外說明使用情況。這可能是違反封裝... – Oded

1

另一種選擇,你可能是一個靜態類和方法

public static class1(string songPath) 
{ 
    public static System.Media.SoundPlayer play(string songPath) 
    { 
     System.Media.SoundPlayer songPlayer = new System.Media.SoundPlayer(songPath); 
     // play here ? 
     // or return to play 
     return songPLayer; 
    } 
}